This is a function I am using to calculate the direction vector between a part in the tool and the player’s mouse.Hit.p
Why does it print out (NAN,NAN,NAN)? I am not very great at vector math so help is appreciated
Please add your code textually to the post rather than taking a screenshot of it. Right now no one can copy-paste your code to make corrections.
First of all, you can leave out the constructor, a simple subtraction will work:
local vector = (mouse.Hit.p - tool.SpawnPart.CFrame.Position).unit
The reason why you are getting a NaN vector (not a number) is because the part between ( ) ends up to be Vector3.new(0,0,0), and then you are trying to normalize (by doing .unit) a vector with 0 length, which is undefined, thus (NaN, NaN, NaN).
To fix this you should define a fallback default direction for when the vector between ( ) is near-zero length, or make sure that it can never end up being a vector of near-zero length.
Example of a solution:
local vector = mouse.Hit.p - tool.SpawnPart.CFrame.Position
if vector.magnitude < .001 then
vector = Vector3.new(0, 0, -1) -- default direction
else
vector = vector.unit
end
Any reason why it’d end up being 0,0,0?
Also, How do I add code textually.
Because apparently it is possible that mouse.Hit.p and tool.SpawnPart.CFrame.Position are the same position in your system. I can’t tell you anything more than that because you gave no details or other code.
I did some further bugtesting and found the error lies directly with the ‘direction’ Vector3. the mouse’s position and the part’s position are not identical.
local mousepos = mouse.Hit.p
local vector = Vector3.new(mousepos - tool.SpawnPart.Position).unit
print(mousepos)
print(tool.SpawnPart.Position)
print(vector)
tool.Server.Event:FireServer(vector)
5.17153025, 4.41138363, -2.49334335 was the spawnpart’s position.
11.6363726, 0, -8.82112217 was the mouse’s position.
NAN, NAN, NAN was the new vector.
There is unfortunately no reference of this variable in the snippet you have given so I can’t help you out further than that. The only way for the given code to produce (NaN, NaN, NaN) is if mouse.Hit.p
and tool.SpawnPart.CFrame.Position
happen to be the same position.
EDIT based on snippet you just edited in
I mentioned this above, don’t do this:
You are passing a vector to Vector3.new here, which does not produce the result you think it does. It will return Vector3.new(0,0,0). You should just write it like this:
local vector = (mousepos - tool.SpawnPart.Position).unit
A solution was found by someone also helping me. It is the “Vector3.new” that was causing the issue. Removing it solved the issue.