I am trying to create a script for my game that tracks the distance a player has moved, but I seem to not be able to find any information on the topic.
How do you track the distance a player has moved?
2 answers
A way you can track the amount a player moved is by using magnitude. The magnitude is essentially the length of the vector.
So what you can do is actually save the original position of the character's HumanoidRootPart, and their current position. From there, we can get the direction vector of those two positions by subtracting both vectors. Finally, use magnitude to get the length of this direction vector.
local PS = game:GetService("Players")
local Player = PS.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local RootPart = Character.HumanoidRootPart
local LastPosition = RootPart.Position
local distance = 0
while true do
--Lower the wait time for more precise measurements.
wait(1)
local CurrentPosition = RootPart.Position
--Here we get the length of the direction vector by using magnitude.
local length = (LastPosition - CurrentPosition).magnitude
--Add to the total number of distance.
distance = distance + length
--Update make CurrentPosition into LastPosition
LastPosition = CurrentPosition
print(Player.Name.." has moved for "..distance.." studs.")
end
This is obviously in a LocalScript. If you really wanted to track the player's movement through the server, it is recommended to create a leaderstats value, and you can track the distance through the Player.CharacterAdded event.
There should be a StarterCharacterScripts script, like this:
local PreviousPosition, ActualPosition = script.Parent.HumanoidRootPart.Position
local DistanceMoved = 0;
while wait() do
ActualPosition = script.Parent.HumanoidRootPart.Position
DistanceMoved = DistanceMoved + ((ActualPosition.X + ActualPosition.Z) - (PreviousPosition.X + PreviousPosition.Z)).magnitude
PreviousPosition = ActualPosition
end
What it does is that it has two variables, one which tracks the previous position, and the other one which tracks the actual position inside the while loop.
Inside the while loop the actual position is set again, so in some cases it should be different, and then the DistanceMoved variable gets bigger with the distance movedby the character, which is the opperation ((ActualPosition.X + ActualPosition.Z) - (PreviousPosition.X + PreviousPosition.Z)).magnitude.
2 comments
you need to explain the script.
I think you forgot to include .Magnitude
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
https://forum.scriptinghelpers.org/topic/763/how-magnitude-works-in-layman-s-terms