# How to target moving object in 2D game

I am working on targeting system for 2D game. Two objects move in space. Each one have Position and Velocity vector. Ship object shoots moving objects in space. Ship can shoot in any direction, but Ship Velocity is added to projectile Velocity.

I read some tutorials and I know the solution is quadratic equation. Moreover I implemented one solution and I achived 75% hits, but sometimes my projectiles fly behind or before object. Also I am not sure how it works underneath... I understend quadratic equation from math lessons but I don't see how it is related to that target calculation. Can some explain in on some drawing? I totaly can't understand why a,b,c parameters looks like they look.

Here is my code:

        Ship.World.Query(boundingBox), objects);

Vector3 shipToTarget = Vector3.Forward;

WorldObject closestObject = GetClosestAsteroid(objects);

Vector3 aimSpot = Vector3.Forward;
Vector3 bulletPath = Vector3.Forward;
float a, b, c;
float p, q;

float t1, t2, t;

float timeToImpact = 0;

if (closestObject != null)
{
shipToTarget = closestObject.Position - Ship.Position;
a = closestObject.LinearVelocity.X * closestObject.LinearVelocity.X + closestObject.LinearVelocity.Z * closestObject.LinearVelocity.Z - (40 * 40) - (Ship.LinearVelocity * Ship.LinearVelocity).Length();
b = 2 * (closestObject.LinearVelocity.X * (closestObject.Position.X - Ship.Position.X) + closestObject.LinearVelocity.Z * (closestObject.Position.Z - Ship.Position.Z));
c = (closestObject.Position.X - Ship.Position.X) * (closestObject.Position.X - Ship.Position.X) + (closestObject.Position.Z - Ship.Position.Z) * (closestObject.Position.Z - Ship.Position.Z);

p = -b / (2 * a);
q = (float)Math.Sqrt((b * b) - 4 * a * c) / (2 * a);

t1 = p - q;
t2 = p + q;

if (t1 > t2 && t2 > 0)
{
t = t2;
}
else
{
t = t1;
}

aimSpot = closestObject.Position + closestObject.LinearVelocity*t ;
bulletPath = aimSpot - (Ship.Position + Ship.LinearVelocity * t);

Ship.Shoot(Vector3.Normalize(bulletPath));

}

• What reference did you use to implement this? – Leo Sep 12 '16 at 17:14
• I do not remember but it probably there is a bug in this logic. But it is worth to mention that this is based on quadratic function equation and parabolic function. – Kacper Kleczewski Sep 14 '16 at 10:01
• What really irks me is that I don't see the speed of the bullet anywhere, which has a great impact in calculating where the bullet and enemy will hit. – Leo Sep 14 '16 at 14:48