Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@brihernandez
Last active June 1, 2021 03:49
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save brihernandez/b214190d832ee9fc4296ebe7740530b2 to your computer and use it in GitHub Desktop.
Save brihernandez/b214190d832ee9fc4296ebe7740530b2 to your computer and use it in GitHub Desktop.
Computes a point for a gun to aim at in order to hit a target using linear prediction.
/// <summary>
/// Computes a point for a gun to aim at in order to hit a target using linear prediction.
/// Assumes a bullet with no gravity or drag. I.e. A bullet that maintains a constant
/// velocity after it's been fired.
/// </summary>
public static Vector3 ComputeGunLead(Vector3 targetPos, Vector3 targetVel, Vector3 ownPos, Vector3 ownVel, float muzzleVelocity)
{
// Extremely low muzzle velocities are unlikely to ever hit. This also prevents a
// possible division by zero if the muzzle velocity is zero for whatever reason.
if (muzzleVelocity < 1f)
return targetPos;
// Figure out ETA for bullets to reach target.
Vector3 predictedTargetPos = targetPos + targetVel;
Vector3 predictedOwnPos = ownPos + ownVel;
float range = Vector3.Distance(predictedOwnPos, predictedTargetPos);
float timeToHit = range / muzzleVelocity;
// Project velocity of target using the TimeToHit.
Vector3 leadMarker = (targetVel - ownVel) * timeToHit + targetPos;
return leadMarker;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment