I am trying to do a simple AI Controller, which fires Missiles at the surrounding targets in the Scene.
- The AI Controller can fire projectiles when moving or stationary.
- The Targets are either stationary or move around in the scene with a Constant Velocity and can't fire projectiles.
I did some searching on Stack overflow and came up with this code to find the direction the AI controller must fire the projectile (constant speed) to hit a target travelling at a constant velocity(it can also be stationary):
private bool GetProjectileDirection(GObject target, GObject source, out Vector3 direction)
{
// Initialize direction to Zero
direction = Vector3.zero;
// The Relative Position between the AI Controller and the target.
Vector2 w = new Vector2(target.Position.x - source.Position.x, target.Position.y - source.Position.y);
// The Relative Velocity between the source and the target.
Vector2 v = new Vector2(target.Velocity.x - source.Velocity.x, target.Velocity.y - source.Velocity.y);
// Quadratic Equation Co-efficients
float a = Vector2.Dot(v, v) - BULLET_SPEED * BULLET_SPEED;
float b = Vector2.Dot(w, v);
float c = Vector2.Dot(w, w);
float root = (b * b) - (a * c);
// The Problem seems to occur here as this becomes less than zero most of the time,
// and exits the function.
// But on the screen, the object is well within the range for the AI to fire at it
if (root < 0)
return false;
// If root < 0, then this becomes NaN and brings the simulation to a crawl
double t = (-b - Math.Sqrt(root)) / a;
double shootX = w.x + t * v.x;
double shootY = w.y + t * v.y;
double theta = Math.Atan2(shootY, shootX);
direction = BULLET_SPEED * new Vector3(Math.Cos(theta), 0, Math.Sin(theta));
return true;
}
I am pretty sure I am missing something. I just can't pinpoint what exactly is it. As a result, the AI seems to miss most of the targets around it.
if(root < 0)
. \$\endgroup\$