Skip to content

Instantly share code, notes, and snippets.

@oyagci
Forked from brihernandez/ComputeGunLead.cs
Created March 24, 2021 19:56
Show Gist options
  • Save oyagci/bbd4452c1388c9c3f63521d523bc8be1 to your computer and use it in GitHub Desktop.
Save oyagci/bbd4452c1388c9c3f63521d523bc8be1 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