Skip to content
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions Assets/Scripts/ProjectileMath.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,9 +61,20 @@ public static float TimeOfFlight(float speed, float angle, float yOffset, float
{
float ySpeed = speed * Mathf.Sin(angle);

float time = (ySpeed + Mathf.Sqrt((ySpeed * ySpeed) + 2 * gravity * yOffset)) / gravity;
float discriminant = (ySpeed * ySpeed) - 2 * gravity * yOffset;
if (discriminant < 0f)
return float.NaN; // no valid solution

return time;
float sqrtDisc = Mathf.Sqrt(discriminant);

// Two possible times: (ySpeed ± sqrtDisc) / gravity
float t1 = (ySpeed + sqrtDisc) / gravity;
float t2 = (ySpeed - sqrtDisc) / gravity;

// Return the positive, larger one (impact time)
float time = Mathf.Max(t1, t2);

return time >= 0f ? time : float.NaN;
}

/// <summary>
Expand Down