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

How can I change my code to only Sprint if your Moving?

I have a problem that if you hold LeftShift down to Sprint and let go of "W" you'll stop sprinting but your Stamina/Energy will still drain... I believe it's in this part of the code

-- Sprint key pressed or released
replicatedStorage.RemoteEvents.Sprint.OnServerEvent:Connect(function(player, state)
	local humanoid = player.Character.Humanoid
	
	if state == "Began" and humanoid:GetState() == Enum.HumanoidStateType.RunningNoPhysics and humanoid.MoveDirection.Magnitude > 0 then
		sprintingPlayers[player.Name] = humanoid.WalkSpeed
		humanoid.WalkSpeed = humanoid.WalkSpeed * sprintModifier
	elseif state == "Ended" and sprintingPlayers[player.Name] then
		humanoid.WalkSpeed = sprintingPlayers[player.Name]
		sprintingPlayers[player.Name] = nil
	end
end)

but I am not sure how to go about it. Basically I want you to be able to hold LeftShift down as much as you'd like but only use your Stamina/Energy if you're actually moving. If you need to see more code just ask. Thanks in advance for any help/feedback!

[EDIT] After messing around I think maybe it's in this section of code?

-- Sprint Key Pressed
userInputService.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift then
			replicatedStorage.RemoteEvents.Sprint:FireServer("Began")
	end
end)

-- Sprint Key Released
userInputService.InputEnded:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.LeftShift then
		replicatedStorage.RemoteEvents.Sprint:FireServer("Ended")
	end
end)

2 comments

0

You can try checking if the player's rootpart's velocity is non-zero.

0

Do you mean setting up a variable like [local velocity = humanoid.RootPart.Velocity] And if so how would I implement it?

1 answer

-- Sprint key pressed or released
replicatedStorage.RemoteEvents.Sprint.OnServerEvent:Connect(function(player, state)
    local humanoid = player.Character.Humanoid

    if state == "Began" and humanoid:GetState() == Enum.HumanoidStateType.RunningNoPhysics and humanoid.MoveDirection.Magnitude > 1 then
        sprintingPlayers[player.Name] = humanoid.WalkSpeed
        humanoid.WalkSpeed = humanoid.WalkSpeed * sprintModifier
    elseif state == "Ended" and sprintingPlayers[player.Name] then
        humanoid.WalkSpeed = sprintingPlayers[player.Name]
        sprintingPlayers[player.Name] = nil
    end
end)

then change that if you walk Enum.HumanoidStateType.RunningNoPhysics and humanoid.MoveDirection.Magnitude it is smaller than 1.

I think this may help I do not know.

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