.Unit printing a correct value then prints 'nan,nan,nan'

was working on AI for one of my game projects and i realised the raycast kept failing almost every second or first cast despite the humanoid which the ai was hostile at was in a reasonable position.


print((v.Position - humanoidRootPart.Position).Unit)
				local result = game:GetService("Workspace"):Blockcast(humanoidRootPart.CFrame, Vector3.new(2,2,2), (v.Position - humanoidRootPart.Position).Unit, raycastParams)

The two positions are identical to each other. So when you get the unit of the difference between the two, since the inner Unit calculation doesn’t know how to actually calculate a position with a magnitude of 0, it’ll default to nil, or NaN. You can test it yourself when you run these lines into the command bar:

The reason is that a unit vector of any vector value REQUIRES the unit’s magnitude to be equal to 1, so it’ll adjust the XYZ properties of the vector to equate the magnitude of 1.

Okay, well if that’s the case, how do I fix it?

So, what I would do in this case is either check if the two positions equal to each other or if their magnitude equals 0. If they do, then you would change the unit into Vector3.zero or something else you would want to do.

local diff = v.Position - humanoidRootPart.Position
local direction = diff.Magnitude == 0 and Vector3.zero or diff.Unit

local result = game:GetService("Workspace"):Blockcast(humanoidRootPart.CFrame, direction, raycastParams)

Hopefully this helps, and good luck on your project. (Make sure to mark as solution to help others with a similar problem)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.