# Projectile motion based off angle

I was using this code to hit an object that is moving horizontally(from right to left) and player on the left is throwing bullets to hit the object.But, what I am finding difficult is projectile motion based off angle(since the object that is to be hit is moving and I can not just keep throwing projectile at the same angle).

Here is what I was using that does not seem to work since the angle is fixed.

How to modify this code so that the angle is changed and not the velocity

IEnumerator project()
{    yield return new WaitForSeconds(0.25f);
float target_Distance = Vector3.Distance(mytransform.position, target.position);
// Calculate the velocity needed to throw the object to the target at specified angle.
float projectile_Velocity = target_Distance / (Mathf.Sin(2 * firingAngle * Mathf.Deg2Rad) / gravity);

// Extract the X  Y componenent of the velocity
float Vx = Mathf.Sqrt(projectile_Velocity) * Mathf.Cos(firingAngle * Mathf.Deg2Rad);
float Vy = Mathf.Sqrt(projectile_Velocity) * Mathf.Sin(firingAngle * Mathf.Deg2Rad);

// Calculate flight time.
float flightDuration = target_Distance / Vx;

// Rotate projectile to face the target.
mytransform.rotation = Quaternion.LookRotation(target.position - mytransform.position);

float elapse_time = 0;

while (elapse_time < flightDuration)
{
mytransform.Translate(0, (Vy - (gravity * elapse_time)) * Time.deltaTime, Vx * Time.deltaTime);

elapse_time += Time.deltaTime;

yield return null;
}

• How is your firingAngle fixed? You may try to assign different values to it and check the results. – S.C. Jul 23 '14 at 16:46
• No no, that would again be fixing the angle. I want it to be dynamically determined based on the changing position of object – Simran kaur Jul 23 '14 at 16:49
• Can the firingAngle simply depend on the xy-offset of the target to the turret? – S.C. Jul 23 '14 at 16:57
• @AldourCheng : I doubts if that's really needed or would make much difference since I am already making the buller face the enemy by using LookAt function in Unity – Simran kaur Jul 23 '14 at 19:59
• Are you working on having your bullet to hit a moving object? If so, I think you need to calculate the position of the object after a certain period of time first. Without a correct measurement of the displacement, I doubt if the bullet can predict the trajectory of the moving object flawlessly. – S.C. Jul 24 '14 at 2:56