Last active
June 1, 2021 03:49
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/// <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