Calculating distance walked with magnitude adds an extra 250 or so studs every time the character is loaded

Hello. I’m writing a simple system to calculate the distance a player has walked. Currently, this is my code:

local RunService = game:GetService("RunService")
local Players = game:GetService("Players")
local walked = game:GetService("ReplicatedStorage"):WaitForChild("Walked")
local function zeroYV3(v3: Vector3) 
	return Vector3.new(v3.X, 0, v3.Z)
end
local function onPlayerAdded(plr)
	local travelled = 0
	local function onCharacterAdded(Character) 
		local humanoid = Character:WaitForChild("Humanoid")
		local rootP = Character:WaitForChild("HumanoidRootPart")
		local pos = rootP.Position
		local Connection
		Connection = RunService.Heartbeat:Connect(function() 
			if humanoid.Health > 0 then 
				local newP  = rootP.Position
				travelled += (zeroYV3(newP) - zeroYV3(pos)).Magnitude
				pos = newP
				walked:FireClient(plr, travelled)
			else
				Connection:Disconnect()
			end
		end)
	end
	plr.CharacterAdded:Connect(onCharacterAdded)
end

for _, player in ipairs(Players:GetPlayers()) do 
	onPlayerAdded(player)
end
Players.PlayerAdded:Connect(onPlayerAdded)

It works fine, except for one thing, every time the CharacterAdded event is fired, the travelled distance is increased by ~250-260 studs.
I’m also using a SpawnLocation. I have a suspicion this is what is causing the problem

try making new calculator, but inside StarterCharacterScript, so it doesnt run unless the character is loaded, and just send += 1 to a number value u stored inside player(not character) everytime he walk 1 stud

this works
distance

put this inside StarterCharacterScript

I found the solution. The SpawnLocation was around 250 studs away from the default spawn point, so it counted the intial teleport from the default spawn. I just waited until the player was “near” the spawnlocation to start measuring.

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