The code here works pretty well:

http://www.kirupa.com/forum/showthread.php?347334-Aiming-and-hitting-a-moving-targetI'm not sure what this bit of code is for though:

// Check we're not breaking into complex numbers

var q:Number = b * b - 4 * a * c;

if (q < 0) return null;

I got rid of it when converting the algorithm for my program and it seems to work fine. Any clues?

Also, what, how and why is the question mark used for in this bit of code:

var t:Number = ((a < 0 ? -1 : 1)*Math.sqrt(q) - b) / (2 * a);

Here is the full code copied over from their website for posterity:

/**

* Shoot at a target

*

* @param t The target to be shot

* @return The bullet to be fired (or null if cannot hit)

*/

public function shoot(targ:Target, bulletSpeed:Number = BULLET_SPEED):Bullet

{

var dx:Number = targ.x - this.x;

var dy:Number = targ.y - this.y;

var a:Number = targ.vx * targ.vx + targ.vy * targ.vy - bulletSpeed * bulletSpeed;

var b:Number = 2 * (targ.vx * dx + targ.vy * dy);

var c:Number = dx * dx + dy * dy;

// Check we're not breaking into complex numbers

var q:Number = b * b - 4 * a * c;

if (q < 0) return null;

// The time that we will hit the target

var t:Number = ((a < 0 ? -1 : 1)*Math.sqrt(q) - b) / (2 * a);

// Aim for where the target will be after time t

dx += t * targ.vx;

dy += t * targ.vy;

var theta:Number = Math.atan2(dy, dx);

// Fire the bullet

var bullet:Bullet = new Bullet();

bullet.target = targ;

bullet.hitPoint = new Point(targ.x + targ.vx * t, targ.y + targ.vy * t);

bullet.x = this.x;

bullet.y = this.y;

bullet.vx = bulletSpeed * Math.cos(theta);

bullet.vy = bulletSpeed * Math.sin(theta);

return bullet;

}