Page 1 of 1

(C++) Aiming: Lead angle/vector to target

Posted: Fri Feb 03, 2006 11:10 am
by Xaron
Hi everyone,

this is a short piece of code for all of you who want to create some kind of space shooter or whatever. ;)

If you have a moving target and have some projectiles which have a speed (don't fly with unlimited speed) you want to know where to aim to hit the target. You need some lead angle/vector.
Well, this piece of code does the computation for this:

Code: Select all

/** 
 * @brief computes the aiming vector in 3d space to hit a target 
 * 
 * @param origin          - absolute position of the player
 * @param targetPos       - absolute position of the target
 * @param targetVel       - velocity of the target (as a vector) in meters/sec
 * @param projectileSpeed - speed of the projectile in meters/sec
 * 
 * @return aimingVector    - current absolute position of the rendezvous (meeting point)
 *                           of the projectile and the target
 * 
 *******************************************************************************************************/
core::vector3df computeAimingVector( core::vector3df& origin, core::vector3df& targetPos,
                                     core::vector3df& targetVel, float projectileSpeed )
{
  // get the vector to the target
  core::vector3df toTargetVec = targetPos - origin;

  // compute the discriminant of the term for the time.
  // If it's less than zero, it's impossible to hit the target.
  // This might happen, if the target is faster than the projectile.
  // In that case we return just the target vector.
  float discriminant = projectileSpeed * projectileSpeed * toTargetVec.getLengthSQ()
    - ( toTargetVec.crossProduct( targetVel ) ).getLengthSQ();
  if( discriminant < 0.0f )
    return targetPos;

  // Compute the target-hit-time
  float fTime = ( sqrtf( discriminant ) + toTargetVec.dotProduct( targetVel ) )
    / ( projectileSpeed * projectileSpeed - targetVel.getLengthSQ() );

  // return target (aiming) vector
  return targetPos + targetVel * fTime;
}
Regards - Xaron

Posted: Fri Feb 03, 2006 4:20 pm
by omaremad
thanks!

Re: (C++) Aiming: Lead angle/vector to target

Posted: Wed Feb 11, 2015 10:56 am
by xboxxerr
Thanking you for sharing

Re: (C++) Aiming: Lead angle/vector to target

Posted: Tue Mar 17, 2015 12:47 am
by chronologicaldot
Yes, thank you!
Old piece of code, but still useful.
Nice find, xboxerr