Sprinting script (with energy)

I have a sprinting script in my game. They simply press shift and this causes their speed to increase, then when they press it again I return it to normal.

The issue is, I want whenever they sprint, for them to lose energy. How can I detect so that it only drains energy when they are moving, and not when they are simply standing still or jumping?

1 Like

This will help you a bit, when the player is walking. This also comes with a speed parameter so when the player is at your sprinting speed, you can decrease stamina

I’m bored so I made a script for you:

local Player = game.Players.LocalPlayer
local Character = Player.Character or Player.CharacterAdded:Wait()
local Humanoid = Character:FindFirstChildOfClass("Humanoid")

local Stamina = 1000
local RunningSpeed = 32

local function onRunning(speed)
    while speed >= 32 do
    task.wait(0.5)
    Stamina -= (Stamina*0.005)
end

Humanoid.Running:Connect(onRunning)

Don’t forget a wait statement as the stamina will deplete in an instant. I have not personally used this, but if I read the documentation correctly, the event fires if the “is running” changes, so have some kind of boolean as well to deny repetitive while loops.

Step 1: Initial Setup To begin with, we need to get references to several important objects in the game.

local player = game.Players.LocalPlayer
local character = player.Character or player.CharacterAdded:Wait()
local humanoid = character:WaitForChild("Humanoid")
local userInputService = game:GetService("UserInputService")
local replicatedStorage = game:GetService('ReplicatedStorage')

Step 2: Define Variables Define variables for the endurance system and sprinting speed. Endurance will be the resource consumed when sprinting, and it will recover over time when not sprinting.

local endurance = 100 
local enduranceRecoveryRate = 1
local enduranceConsumptionRate = 2
local sprintSpeedMultiplier = 1.5
local normalSpeed = humanoid.WalkSpeed
local sprinting = false

Step 3: Stamina GUI Implement a function to update the stamina GUI. This function will change the size of a bar on the GUI to visually represent the remaining endurance.

local function updateStaminaGUI()
	if endurance > 0 then
		player.PlayerGui.Temperature.Stamina.Frame.Size = UDim2.new(endurance / 100, 0, 1, 0)
	else
		player.PlayerGui.Temperature.Stamina.Frame.Size = UDim2.new(0, 0, 1, 0)
	end
end

Step 4: Update Function Create an update function that will be called every frame. This function will handle the consumption and recovery of endurance, as well as the character’s speed change.

local function onUpdate(step)
	if sprinting then
		if endurance > 0 then
			endurance = math.max(endurance - enduranceConsumptionRate * step, 0)
			updateStaminaGUI()
		else
			sprinting = false
		end
	elseif endurance < 100 then
		endurance = math.min(endurance + enduranceRecoveryRate * step, 100)
		updateStaminaGUI()
	end
end

Step 5: Input Handling Create an input function to handle when the player presses or releases the sprint key (in this case, the Left Shift key). This function will set the sprinting variable and adjust the character’s speed accordingly.

local function onInput(input, gameProcessed)
	if input.KeyCode == Enum.KeyCode.LeftShift and not gameProcessed then
		if input.UserInputState == Enum.UserInputState.Begin and endurance > 0 then
			sprinting = true
		elseif input.UserInputState == Enum.UserInputState.End or endurance <= 0 then
			sprinting = false
		end
	end
end

Step 6: Connect to Events Connect the input and update functions to the appropriate events so that they will be called at the right times.

local IBUI = userInputService.InputBegan:Connect(onInput)
local IEUI = userInputService.InputEnded:Connect(onInput)
local HB = game:GetService("RunService").Heartbeat:Connect(onUpdate)

Step 7: Character Death Handling Finally, implement a function to disconnect all of the event connections when the character dies.

humanoid.Died:Connect(function()
	if IBUI then
		IBUI:Disconnect()
	end
	if IEUI then
		IEUI:Disconnect()
	end
	if HB then
		HB:Disconnect()
	end
end)

And now set up the server script:

First, get references to the necessary services:

local replicatedStorage = game:GetService('ReplicatedStorage')

Step 2: Create Remote Event Next, create a Remote Event within ReplicatedStorage. This will allow the server to receive events fired from the client.

local sprintEvent = Instance.new("RemoteEvent")
sprintEvent.Name = "Sprint"
sprintEvent.Parent = replicatedStorage.Events

Step 3: Define Sprint Event Now, we will define what happens when the sprint event is fired. In this case, we’re changing the player’s walk speed based on the value passed from the client.

local function onSprintEvent(player, speed)
    local character = player.Character
    if character then
        local humanoid = character:FindFirstChild("Humanoid")
        if humanoid then
            humanoid.WalkSpeed = speed
        end
    end
end

Step 4: Connect to Sprint Event Connect the function to the sprint event so that it will be called whenever the event is fired.

sprintEvent.OnServerEvent:Connect(onSprintEvent)

Now, the server is set up to receive the sprint event from the client and change the player’s speed accordingly.

Remember, this is just the server-side script. It works in tandem with the client-side script you’ve written previously. The client-side script is responsible for detecting when the player wants to sprint and firing the sprint event, and the server-side script is responsible for receiving that event and changing the player’s speed.

Please note that networked communication should be used wisely to prevent cheating or exploiting. Always validate data coming from clients on the server.

2 Likes