rigidbody.velocity assign attempt for ‘Item(Clone)’ is not valid. Input velocity is { NaN, NaN, NaN }.
It works most of the time but sometimes I get this error. I’m normalizing the direction before I multiply it with the force.
Basically I’m setting the velocity to the output of this function:
private Vector3 SimulateProjectile(Vector3 target)
{
Rigidbody.drag = 0f;
Rigidbody.useGravity = true;
float firingAngle = 45.0f;
var dir = target - startTransform.position; // get target direction
var h = dir.y; // get height difference
dir.y = 0; // retain only the horizontal direction
var dist = dir.magnitude; // get horizontal distance
var a = firingAngle * Mathf.Deg2Rad; // convert angle to radians
dir.y = dist * Mathf.Tan(a); // set dir to the elevation angle
dist += h / Mathf.Tan(a); // correct for small height differences
// calculate the velocity magnitude
var vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
return vel * dir.normalized;
}
I printed out the values of those equations to make sure and they’re never 0. I get the error when both of those values are 1. I mean the firing angle is always the same - I’m setting it to 45 in that code so those tan and sin 2 * a can’t be 0.
Using that I found out that at this point, it becomes NaN:
var vel = Mathf.Sqrt(dist * Physics.gravity.magnitude / Mathf.Sin(2 * a));
That’s because dist * Physics.gravity.magnitude / Mathf.Sin(2 * a) is negative.
I need to find some new calculation that works on large height differences (now I understand that comment). Unfortunately the ones I’ve found don’t work for some reason.
Well, the square root of a negative number is an imaginary number which will result in NAN. Use Mathf.Abs and (if directionaility is important``) ``Mathf.Sign instead:
But directionality is important. Getting the absolute value was the first thing I tried after I realized that dist being negative was causing these problems and the result was worse than NAN.