Skip to content

Instantly share code, notes, and snippets.

@stevewoolcock
Last active April 13, 2022 03:48
Show Gist options
  • Save stevewoolcock/df0eff673ca32a1f6b5630e4ff1838fb to your computer and use it in GitHub Desktop.
Save stevewoolcock/df0eff673ca32a1f6b5630e4ff1838fb to your computer and use it in GitHub Desktop.
Trajectory Functions
/// <summary>
/// Gets a position along a parabolic trajectory, given an origin and initial velocity.
/// </summary>
/// <param name="origin">The origin point.</param>
/// <param name="initialVelocity">The initial velocity.</param>
/// <param name="gravity">The gravity acceleration.</param>
/// <param name="t">The time along the curve (0...1).</param>
/// <returns>The position along the parabola at time <paramref name="t"/>.</returns>
public Vector3 Parabola(Vector3 origin, Vector3 initialVelocity, float gravity, float t)
{
var x = origin.x + initialVelocity.x * t;
var z = origin.z + initialVelocity.z * t;
var y = (-0.5f * gravity * t * t + initialVelocity.y * t) + origin.y;
return new Vector3(x, y, z);
}
/// <summary>
/// Gets a position along a parabolic trajectory, from an origin to a destination point.
/// </summary>
/// <param name="origin">The origin point.</param>
/// <param name="destination">The destination point.</param>
/// <param name="angle">The angle of the arc, in radians.</param>
/// <param name="t">The time along the curve (0...1).</param>
/// <returns>The position along the parabola at time <paramref name="t"/>.</returns>
private Vector3 ParabolaToFrom(Vector3 origin, Vector3 destination, float angle, float t)
{
var delta = destination - origin;
var distance = Mathf.Sqrt(delta.x * delta.x + delta.z * delta.z);
var tanTheta = Mathf.Tan(angle);
return new Vector3
{
x = origin.x + t * delta.x,
z = origin.z + t * delta.z,
y = (t * distance * (1 - t) * tanTheta) + (t * t * delta.y) + origin.y
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment