Scripting HelpersARCHIVE
A little piece of Roblox history. Preserved for everyone, one question at a time.Read about the archive →
COMMUNITY QUESTION

How to make a maximum speed limit?

So I have script that increases the characters speed while they run, but I want to have a maximum speed that it cant go above.

Script:

local Players = game.Players
local RunService = game:GetService("RunService")
 
local SpeedPerStud = 0.08 --Configure this to your liking!!!!!
 
local StudsTraveled = 0
local LastPosition = nil
 
function playerAdded(player)
	--Fires when a player joins the server
	local Speed = Instance.new("NumberValue") --In case the player dies, save their speed
	Speed.Name = "SpeedValue"
	Speed.Value = 0.6
	Speed.Parent = player
	local RootPartHeartbeat = nil
	player.CharacterAdded:Connect(function(character)
		LastPosition = character.HumanoidRootPart.Position
		RootPartHeartbeat = RunService.Heartbeat:Connect(function()
			if character:FindFirstChild("HumanoidRootPart") then --If the player jumps into the void or their character doesn't exist for some reason, this will stop this block of code from running
				local DistanceFromLastPosition = (character.HumanoidRootPart.Position-LastPosition).magnitude
				Speed.Value = Speed.Value+(DistanceFromLastPosition*SpeedPerStud)
				character.Humanoid.WalkSpeed = Speed.Value
				LastPosition = character.HumanoidRootPart.Position
			end
		end)
	end)
	player.CharacterRemoving:Connect(function()
		RootPartHeartbeat:Disconnect() --Prevents **serious** memory leaks AND errors!
	end)
end
 
Players.PlayerAdded:Connect(playerAdded)

5 comments

0

I'm new to coding but couldn't you make something like "if speed > (maxSpeed) then Speed = maxSpeed"?

0

Or maybe just tween the speed lmao

0

You're literally making them faster the further they leave the origin Vector, that's ridiculous

0

What use is this for?!

0

A Sonic game lmao

1 answer

Add a max_speed variable:

max_speed = 16 -- default roblox walkspeed, can increase

then in your function, do this:

local DistanceFromLastPosition = (character.HumanoidRootPart.Position-LastPosition).magnitude
if Speed.Value >= max_speed then
	Speed.Value = max_speed
elseif Speed.Value < max_speed then -- elseif function to ensure Speed.Value can't be compared when it's nil or max_speed isn't nil
	Speed.Value = Speed.Value+(DistanceFromLastPosition*SpeedPerStud)
	character.Humanoid.WalkSpeed = Speed.Value
	LastPosition = character.HumanoidRootPart.Position
end

Accept answer if it works! (Optional)

This discussion is preserved as it was. New answers, comments, and votes are closed.