- Home /
Projectile shooting with range, height & flight time to display in UI
I am creating this game by using Leap motion controller, my right hand is Cannon, it shoots cannonballs when the gesture is recognized. Speed of the ball is cannon shots speed & Force on impact is the force calculated on impact which is all working fine but when I am trying to get the correct values of projectile motion such as Range, Height of projectile and Flight duration my logic seems to vanish. I am pretty sure my logic is wrong. I am a beginner in game development. Below is code I am using:
public float gravity = 9.98f;
public Transform firingCannon;
public Text flightTime;
public Text projectileSpeed;
public Text projectileDistance;
public Text RangeofProjectile;
public Transform MyPosition;
private Transform myTransform;
public Transform Target;
void Start()
{
StartCoroutine(CalcSpeed());
StartCoroutine(CalcFlightTime());
}
private IEnumerator CalcFlightTime()
{
bool isPlaying = true;
while (isPlaying)
{
Vector3 prevPos = transform.position;
yield return new WaitForFixedUpdate();
float ProjectileVelocity = Mathf.RoundToInt((Vector3.Distance(transform.position, prevPos) / Time.fixedDeltaTime) / (Mathf.Sin(2 * firingCannon.eulerAngles.z * Mathf.Deg2Rad) / gravity));
projectileSpeed.text = "Projectile Range: " + ProjectileVelocity + " m";
float Vx = Mathf.Sqrt(ProjectileVelocity) * Mathf.Cos(firingCannon.eulerAngles.z * Mathf.Deg2Rad);
float Vy = Mathf.Sqrt(ProjectileVelocity) * Mathf.Sin(firingCannon.eulerAngles.z * Mathf.Deg2Rad);
//projectileSpeed.text = "Velocity of Projectile: " + ProjectileVelocity + " m/s";
float velocity = Mathf.Sqrt(Vx * Vx + Vy * Vy);
// Calculate flight time.
float flightDuration = Vector3.Distance(transform.position, prevPos) / Vx;
projectileDistance.text = "Projectile Duration: " + Vx + " m";
//float elapse_time = 0;
float TotalflightTime = 2 * Vy / gravity;
flightTime.text = "Total Flight Duration: " + Vy + " s";
float Range = velocity * Mathf.Sin(firingCannon.eulerAngles.z * firingCannon.eulerAngles.z);
RangeofProjectile.text = "Range: " + Range + " m";
}
Your answer
Follow this Question
Related Questions
How to calculate projectile (baseball) distance with drag factor 1 Answer
How to change the Width and Height in the script C#? (New Gui Unity 4.6 beta) 2 Answers
Returning Force/Direction to zero 0 Answers
I shoot a projectile, but its rotation is wrong (c#) 1 Answer
De/activating Gameobject depending on distance from different Activators 1 Answer