Skip to content

Instantly share code, notes, and snippets.

@JakeLunn
Last active April 23, 2023 18:47
Show Gist options
  • Save JakeLunn/6e39c579308a5ce14d0eaecd35a103be to your computer and use it in GitHub Desktop.
Save JakeLunn/6e39c579308a5ce14d0eaecd35a103be to your computer and use it in GitHub Desktop.
Unity, Projectile Motion, Angle Required to Hit Coordinate (X, Y, Z)
public static class PhysicsCalculator
{
// https://en.wikipedia.org/wiki/Projectile_motion#Angle_%CE%B8_required_to_hit_coordinate_(x,_y)
public static float CalculateAngleToHitXYZ(Vector3 from, Vector3 to, float v, float g)
{
g = Mathf.Abs(g); // According to the wikipedia article, g is acceleration due to gravity and is |g|
Vector3 s = (to - from); // Non-normalized so that we only get an angle if the velocity is enough to reach target.
float x = new Vector3(s.x, 0, s.z).magnitude;
float y = s.y;
float v2 = v * v;
float v4 = v2 * v2;
float fac = v4 - g*(g*x*x + 2*y*v2);
if (fac < 0) // Can't reach target with given velocity
{
return Mathf.Infinity;
}
/*
There are two possible launch angles for reaching the target e.g. v2 +- sqrt(fac)
theta1 = High arc angle, for big lobs
theta2 = Low arc angle, for shallow lobs
*/
//float theta1 = Mathf.Atan((v2 + Mathf.Sqrt(fac)) / (g * x)) * Mathf.Rad2Deg;
float theta2 = Mathf.Atan((v2 - Mathf.Sqrt(fac)) / (g * x)) * Mathf.Rad2Deg;
// Returning shallow arc
return theta2;
}
public static float CalculateMaxRangeFromVelocity(float v, float g) => (v*v)/Mathf.Abs(g);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment