Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
2

How do you track the distance a player has moved?

Asked by
Lodok3 18
6 years ago

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.

2 answers

Log in to vote
2
Answered by
Rheines 661 Moderation Voter
6 years ago
Edited 6 years ago

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 magnitudeto get the length of this direction vector.

01local PS = game:GetService("Players")
02local Player = PS.LocalPlayer
03local Character = Player.Character or Player.CharacterAdded:Wait()
04local RootPart = Character.HumanoidRootPart
05 
06local LastPosition = RootPart.Position
07 
08local distance = 0
09 
10while true do
11    --Lower the wait time for more precise measurements.
12    wait(1)
13    local CurrentPosition = RootPart.Position
14    --Here we get the length of the direction vector by using magnitude.
15    local length = (LastPosition - CurrentPosition).magnitude
View all 24 lines...

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.

Ad
Log in to vote
0
Answered by
Vik954 48
6 years ago
Edited 6 years ago

There should be a StarterCharacterScripts script, like this:

01local PreviousPosition, ActualPosition = script.Parent.HumanoidRootPart.Position
02local DistanceMoved = 0;
03 
04while wait() do
05    ActualPosition = script.Parent.HumanoidRootPart.Position
06 
07    DistanceMoved = DistanceMoved + ((ActualPosition.X + ActualPosition.Z) - (PreviousPosition.X + PreviousPosition.Z)).magnitude
08 
09    PreviousPosition = ActualPosition
10end

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.

0
you need to explain the script. yHasteeD 1819 — 6y
0
I think you forgot to include .Magnitude User#5423 17 — 6y

Answer this question