Skip to content

Instantly share code, notes, and snippets.

@forestrf
Forked from brihernandez/ComputeGunLead.cs
Created March 24, 2021 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save forestrf/7598e7fe0e2436171f3de318465d4106 to your computer and use it in GitHub Desktop.
Save forestrf/7598e7fe0e2436171f3de318465d4106 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