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
5 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
5 years ago
Edited 5 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.

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.

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

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.

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

Answer this question