Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How to change the key?

Asked by 9 years ago

I created this script following some instructions but I am not sure how I would change it so that if the F key is hit you sprint but if the F key is hit again you stop sprinting. I also would like an explanation as to how this script exactly works as I see this string stuff and and I am not sure what it even does.

01--Put in Game.StarterPlayer.StarterPlayerScripts
02 
03local player = game.Players.LocalPlayer
04repeat wait() until player.Character
05local character = player.Character
06local mouse = player:GetMouse()
07 
08LastTap = math.floor(tick())
09 
10mouse.KeyDown:connect(function(key)
11    key = key:lower()
12    if key == string.char(48) then
13    character.Humanoid.WalkSpeed = 30
14 
15        end
View all 24 lines...

1 answer

Log in to vote
4
Answered by
EgoMoose 802 Moderation Voter
9 years ago

My first suggestion would be to use the UserInputService since KeyDown and KeyUp are deprecated methods of getting user input.

With that in mind there are two events we need in the UserInputService:

http://wiki.roblox.com/index.php?title=API:Class/UserInputService/InputBegan http://wiki.roblox.com/index.php?title=API:Class/UserInputService/InputEnded

The first event, InputBegan, fires when the user presses a key down or their mouse up. The second event, InputEnded, fires when the user stops pressing a key down or up.

These events also give us something called input objects:

http://wiki.roblox.com/index.php?title=API:Class/InputObject

One of their properties is the KeyCode property:

http://wiki.roblox.com/index.php?title=API:Class/InputObject/KeyCode

It returns an enum of the key pressed (assuming it exists otherwise nil). The enum list can be found here: http://wiki.roblox.com/index.php?title=API:Enum/KeyCode remeber though, intellisense is a life saver sometimes.

That being said, we have a enough information now to solve your problem.

01local player = game:GetService("Players").LocalPlayer;
02local character; repeat wait(); character = player.Character; until character;
03local humanoid = character:WaitForChild("Humanoid");
04 
05local inputService = game:GetService("UserInputService");
06 
07inputService.InputBegan:connect(function(input, process)
08    if process then return; end; -- don't continue if player is in menu or something
09    if input.KeyCode == Enum.KeyCode.LeftShift then -- player pressed the leftshift key
10        humanoid.WalkSpeed = 30;
11    end;
12end);
13 
14inputService.InputEnded:connect(function(input, process)
15    -- same process as above but when the player stops pressing the key
16    if input.KeyCode == Enum.KeyCode.LeftShift then
17        humanoid.WalkSpeed = 16;
18    end;
19end);
0
Thanks! What would the code be though if I wanted to use the F key? Conmmander 479 — 9y
Ad

Answer this question