(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.

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

Postby Xaron » Fri Feb 03, 2006 11:10 am

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.
Posts: 305
Joined: Sun Oct 16, 2005 7:39 am
Location: Germany

Postby omaremad » Fri Feb 03, 2006 4:20 pm

Competition winner
Posts: 1025
Joined: Fri Jul 15, 2005 11:30 pm
Location: Cairo,Egypt

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

Postby xboxxerr » Wed Feb 11, 2015 10:56 am

Thanking you for sharing
Posts: 1
Joined: Wed Feb 11, 2015 10:51 am

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

Postby chronologicaldot » Tue Mar 17, 2015 12:47 am

Yes, thank you!
Old piece of code, but still useful.
Nice find, xboxerr
User avatar
Competition winner
Posts: 545
Joined: Mon Sep 10, 2012 8:51 am

Return to Code Snippets

Who is online

Users browsing this forum: No registered users and 1 guest