This is my first time scripting on Roblox and I have a script that tracks and saves how many studs a player walked. For some reason, it sometimes works and sometimes doesn’t. I have run the program many times and I can’t seem to find a pattern. Upon joining the game, there is a chance it tracks steps/points correctly and the rest of the time, points don’t change and steps stay at 0.
If anybody could identify the issue it would be great!
local spawnLocation = workspace:WaitForChild("SpawnLocation")
local function calculateDistanceFromSpawn(character)
local humanoidRootPart = character:WaitForChild("HumanoidRootPart")
local playerPosition = humanoidRootPart.Position
local spawnPosition = spawnLocation.Position
local distance = (playerPosition - spawnPosition).Magnitude
return distance
end
local function CalculateDistance(character, points, studs)
local HRP = character:WaitForChild("HumanoidRootPart")
local Humanoid = character:WaitForChild("Humanoid")
local HasDied = false
Humanoid.Died:Connect(function() HasDied = true end)
local PreviousPosition = HRP.Position
repeat
task.wait(0.1)
studs.Value = calculateDistanceFromSpawn(character)
local distanceTravelled = (PreviousPosition - HRP.Position).magnitude
if distanceTravelled > 1 then
points.Value += distanceTravelled
PreviousPosition = HRP.Position
end
until HasDied
end
local DataStoreService = game:GetService("DataStoreService")
local playerDataStore = DataStoreService:GetDataStore("PlayerPoints")
game.Players.PlayerAdded:Connect(function(player)
local stats = Instance.new("Folder")
stats.Name = "leaderstats"
stats.Parent = player
local points = Instance.new("NumberValue")
points.Name = "Points"
points.Value = 0
points.Parent = stats
local studs = Instance.new("NumberValue")
studs.Name = "Studs"
studs.Value = 0
studs.Parent = stats
local function savePoints()
local success, error = pcall(function()
playerDataStore:SetAsync(player.UserId .. "_Points", points.Value)
end)
if not success then
warn("Failed to save points for player " .. player.Name .. ": " .. error)
end
end
player.CharacterRemoving:Connect(function(character)
savePoints()
end)
-- Load points if they exist
local storedPoints = playerDataStore:GetAsync(player.UserId .. "_Points")
if storedPoints then
points.Value = storedPoints
end
print(player.Name .. " has connected")
player.CharacterAdded:Connect(function(character)
CalculateDistance(character, points, studs)
end)
end)
If you want to test out the (unfinished) game, it’s here: Infinite Corridor - Roblox
Try joining multiple times to see the randomness of the script working/breaking