Dot product returning NaN?

Recently, I redid the projectiles in Tankery (woo) and they have proper armor angling effects! (wooo!)
However, i’m using the dot product of two vectors, and then running it through Acos to return a number angle.
this is great!.. except… sometimes v1:Dot(v2) is returning NaN
here’s the code

	local Angle = math.acos(V1:Dot(N1))				
	A = A*(1/math.cos(Angle))
	print(V1:Dot(N1),Angle,A)

it’ll sometimes return
-nan -nan -nan

the vectors i’m putting in are already unit vectors, so i’m not sure what i’m doing wrong.

How are you getting those vectors? I had a similar problem with the calculations for my orbital sim. It’s annoying that doing arithmetic on NaN values doesn’t throw any errors.

Are you using any square roots or inverse trigonometry that can produce NaN values?

One is a unit vector of a ray’s direction, the other is the normal of a raycasting return.

I’m not sure why, but switching to Ray.Direction from the vector3 i used to construct it seems to have worked…

A possible reason for this would be that any vector plugged into dot product has to have at least one value greater than zero. Its possible you had some form of discrepancy finding the v1 value which caused it to be zero in all three directions.

2 Likes

Also, math.acos will return NaN for any input greater than 1 or less than -1, so it’s often a good idea to bound the input between -1 and 1:

local dot = V1:Dot(N1)
local Angle = math.acos(math.clamp(dot, -1, 1))

This should protect you from potential floating point errors giving you values like 1.00000000001 that would mess up math.acos.

4 Likes