I am not quite sure how I would create a sprinting script. I read the wiki a few times but it doesn't quite explain how I would do this. I somewhat know what to do but I am not quite sure if I am doing this right or if this is the most efficient way to do this. I have what I think is close to correct below, but any help would be appreciated.
player = game.Players.LocalPlayer while wait() do if (key:byte() == 48 or key:byte() == 47) and (key == "w" or key == "a" or key == "s" or key == "d" or key:byte() == 17 or key:byte() == 18 or key:byte() == 19 or key:byte() == 20) then --checks to see if they have either of the shift keys and any directional key held down player.Character.Humanoid.Walkspeed = 18 else player.Character.Humanoid.Walkspeed = 16 end end
As I stated before, I'm not quite sure if this is relatively right, but I think it's close. Any help is welcome.
Don't worry about the directional keys. If they aren't walking, they won't walk, so there's no real problem of caring what keys they're pressing.
Instead of listening when the keys are pressed, we'll use the humanoid Running event to track it.
key
isn't defined in this script. You would have to use KeyUp
or KeyDown
events on a Mouse
object to find keys being pressed.
In a LocalScript, you can get a mouse handle using
playerMouse = player:GetMouse()
When someone presses shift, we'll increase the WalkSpeed, and when they release shift we'll turn it back down:
sprinting = false playerMouse.KeyDown:connect( function(key) -- key is which key is pressed if key:byte() == 48 or key:byte() == 47 then sprinting = true end end ) playerMouse.KeyUp:connect( function(key) -- key is which key is pressed if key:byte() == 48 or key:byte() == 47 then sprinting = false end end ) walking = false while not player.Character do wait() end -- Wait for character humanoid = player.Character.Humanoid humanoid.Running:connect( function(speed) walking = speed > 16.5 end ) stamina = 100 while wait() do stamina = math.min(100, stamina + 0.5) if sprinting and stamina > 0 then humanoid.WalkSpeed = 18 else sprinting = false end if walking and sprinting then stamina = stamina - 1.5 end end
player = game.Players.LocalPlayer Mouse = player:GetMouse() function thing(key) Key = key:lower() if Key == "w" then print("W was pressed") end end) Mouse.KeyDown:connect(thing)