[Solved] Projectile motion in Unity3d


Let’s be more specific. The projectile is launched from point A and needs to hit B, who is moving horizontally with constant speed in 2D.

This is the position of the projectile, over time:

P.x = A0.x + VP0.x * t
P.y = A0.y + VP0.y * t - g/2 * t^2

And this is the position of B, over time:

B.x = B0.x + VB0.x * t
B.y = B0.y

Where A0 is the position of A, at time 0; B0 is the position of B, at time 0; VB0 is the velocity of B (constant and horizontal only) and VP0 is the velocity with which we’re going to launch the projectile. If we constrain the system by tuning the value of ‘t’ (the time it takes for the projectile to hit B), then we need to resolve VP0. We do this by saying that at collision time, P and B will be equal:

A0.x + VP0.x * t = B0.x + VB0.x * t
A0.y + VP0.y * t - g/2 * t^2 = B0.y

Resolving VP0:

VP0.x = (B0.x - A0.x)/t + VB0.x
VP0.y = (B0.y - A0.y)/t + g/2 * t

Now that we have the velocity for the projectile, simulating it can be done in a straightforward way using the formula above:

// calculate velocity when firing projectile
launchVelocity.x = (b.x - a.x) / desired_time + velocity_b.x;
launchVelocity.y = (b.y - a.x) / desired_time + gravity / 2 * desired_time;

// then for each frame, update position
elapsedTime += dt;
projectile.x = a.x + launchVelocity.x * elapsedTime;
projectile.y = a.y + (launchVelocity.y - gravity / 2 * elapsedTime) * elapsedTime;

One note is that if B is moving towards A, velocity_b can be negative.

solved Projectile motion in Unity3d