Variables are "NaN" for some reason?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By cunuduh

First time on here; forgive me if this is a dumb question, but the variables “prediction”, “delta” and “t” are NaN. I plug the numbers from the equation into a calculator and I get a number, so why do they show as NaN?

Relevant code (C#):

public Vector2 PredictiveAiming() //For leading projectile shots
    var projectileSpeed = speed * GetPhysicsProcessDeltaTime();
    var relativePos = target.GlobalPosition - source.GlobalPosition;
    var theta = relativePos.AngleTo(target.velocity);

    var a = target.velocity.LengthSquared() - (projectileSpeed * projectileSpeed);
    var b = -2.0f * Mathf.Cos(theta) * relativePos.Length() * target.velocity.Length();
    var c = relativePos.LengthSquared();
    var delta = Mathf.Sqrt((b * b) - (4.0f * a * c));
    var t = (-(b + delta)) / (2.0f * a);

    Vector2 prediction = target.GlobalPosition + (target.velocity * t);
    return new Vector2(prediction - source.GlobalPosition);

Do a, b, or c report NaN?

Looking at the maths for delta to be Nan. a, b or c must be NaN.

petermoyle | 2022-09-06 13:56

I logged all of the values. None are NaN except for delta and t

cunuduh | 2022-09-06 19:52

:bust_in_silhouette: Reply From: cunuduh

I fixed it by changingvar delta = Mathf.Sqrt((b * b) - (4.0f * a * c)); to var delta = b - Mathf.Sqrt(4.0f * a * c);. I have no idea why it works when I do that

:bust_in_silhouette: Reply From: Regulus

It could be that (b * b) - (4.0f * a * c) is negative, so when you do Mathf.Sqrt((b * b) - (4.0f * a * c)); it returns NaN, (in real mathematics it would be an imaginary number)

To fix it, i am guessing that maybe one of your a, b, or c variables is negative when it shouldn’t be, causing the “parabola” to have no x-intercepts.