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

Post those lines of code you feel like sharing or find what you require for your project here; or simply use them as tutorials.
Post Reply
Xaron
Posts: 310
Joined: Sun Oct 16, 2005 7:39 am
Location: Germany
Contact:

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

Post 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
Last edited by Xaron on Tue Feb 07, 2006 7:59 am, edited 1 time in total.
omaremad
Competition winner
Posts: 1027
Joined: Fri Jul 15, 2005 11:30 pm
Location: Cairo,Egypt

Post by omaremad »

thanks!
xboxxerr
Posts: 1
Joined: Wed Feb 11, 2015 10:51 am

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

Post by xboxxerr »

Thanking you for sharing
raza
chronologicaldot
Competition winner
Posts: 684
Joined: Mon Sep 10, 2012 8:51 am

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

Post by chronologicaldot »

Yes, thank you!
Old piece of code, but still useful.
Nice find, xboxerr
Post Reply