Magnitude always returns 0

I’m trying to get the distance from the player to an NPC for a distance override. (raycasting returns false when player is not behind walls more than often and so im checking that the player is really behind the wall).

The exact same script works in other NPCs.

Nothing I do seems to fix this. Here’s the parts of the script with magnitude included:

the function

local function getDistance(a, b)
	local distance
	distance = (a.Position - b.Position).Magnitude
	print(distance)
	return distance
end

the usage

local distanceOverride = false
if playerCharacter:FindFirstChild("HumanoidRootPart") and getDistance(playerCharacter.HumanoidRootPart,rootPart) <= 50 then
        print("Distance override.")
	distanceOverride = true
end

getDistance always returns 0, no matter where the player actually is.

What am I doing wrong? Any help would be appreciated, thanks!

1 Like

what exactly is RootPart ??? its probably the player’s humanoidrootpart

1 Like

rootPart is the NPC’s root part. just a variable to make it easier.

Can you show me the variable locals for playerCharacter and rootPart?

1 Like

playerCharacter is the first argument in a ray cast function:

local function CheckRayCast(playerCharacter)

this function is called by a CharacterAdded:Connect() hook, as the NPC needs to recognise when a new player joins the game:

game.Players.PlayerAdded:Connect(function(p)
	p.CharacterAdded:Connect(function(c)
		spawn(function()
			while wait(3) do
				if canChange then
					CheckRayCast(c)
				end
			end
		end)
	end)
end)

canChange is simply ‘is the NPC ready to begin a chase scene?’

rootPart for NPC:

local rootPart = script.Parent:WaitForChild("HumanoidRootPart")

(i am going to change spawn(function() to a coroutine, but it works fine for now)

Try calling the getdistance function on the objects without any ifs to see if that’s functionable

1 Like

Yes, it works. It printed 298 a few times. (i used two walls)

Try that with the HumRootPart and the NPC root part

1 Like

keeps returning 0. they are on other sides of the map.

What’s the primary part of the NPC?

1 Like

after trying outside of a function it returns 286, seems like its just inconsistent? im going to hook it to a bindable event to call it instead.

Function returns correctly once in a module script.

1 Like