From 4779783823b45a418d977d835afbccc9fe0a15c1 Mon Sep 17 00:00:00 2001 From: Kostas Vs Date: Fri, 22 Aug 2025 15:00:32 +0300 Subject: [PATCH] Fix NaN TimeOfFlight at negative yOffset & low angle --- Assets/Scripts/ProjectileMath.cs | 15 +++++++++++++-- 1 file changed, 13 insertions(+), 2 deletions(-) diff --git a/Assets/Scripts/ProjectileMath.cs b/Assets/Scripts/ProjectileMath.cs index fe2f025..fdd3cb9 100644 --- a/Assets/Scripts/ProjectileMath.cs +++ b/Assets/Scripts/ProjectileMath.cs @@ -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; } ///