Everytime the player press Q, it increases their WalkSpeed until it reaches 250. But if I stop pressing Q, my speed keeps going up. The same thing happens for my second function. It makes my WalkSpeed go down until it reaches 20 but if I stop in the middle of it lets say, it'll keep going down. How can I check when the player stops pressing the key so the function can terminate?
01 | local player = game.Players.LocalPlayer |
02 | local char = player.Character |
03 | KeyHeld = false |
04 | KeyHeld 2 = false |
05 |
06 | --When the user presses Q, it'll keep increasing their speed until it reaches 250, so how would I make it so it stops when the user stops pressing Q? |
07 | function onKeyPress(inputObject,gameProcessed) |
08 | if inputObject.KeyCode = = Enum.KeyCode.Q and script.Active.Value = = true then |
09 | KeyHeld = true |
10 | KeyHeld 2 = false |
11 | while KeyHeld do |
12 | if char.Humanoid.WalkSpeed < 250 and char.Humanoid.WalkSpeed > = 20 then |
13 | char.Humanoid.WalkSpeed = char.Humanoid.WalkSpeed + 10 |
14 | end |
15 | wait() |
If you change it such that the InputBegan functions are given to a variable, then you can disconnect the function, therefore stopping it. Idk how to explain but like this
e.g
1 | a = game:GetService( "UserInputService" ).InputBegan:connect(onKeyPress) |
2 | b = game:GetService( "UserInputService" ).InputBegan:connect(onKeyPress 2 ) |
Therefore when you don't want the function to run anymore, you can do either:
1 | a:Disconnect() |
or the other depending on which one you want to stop
something like this? idk im using click detectors for ease it prob work the same for yours
01 | local detector = script.Parent:WaitForChild( 'ClickDetector' ) |
02 | local debounce = false |
03 |
04 | detector.MouseClick:connect( function () |
05 | if debounce = = false then |
06 | debounce = true |
07 | print ( 'how about no' ) |
08 | elseif debounce = = true then |
09 | debounce = false |
10 | print ( 'kid friendly word' ) |
11 | end |
12 | end ) |
your rough example would be:
01 | local plyr = game:GetService( 'Players' ).LocalPlayer |
02 | local mouse = plyr:GetMouse() |
03 |
04 |
05 | mouse.KeyDown:connect( function (key) |
06 | if debounce = = false and key = = 'q' then |
07 | debounce = true |
08 | print ( 'how about no' ) |
09 | elseif debounce = = true and key = = 'q' then |
10 | debounce = false |
11 | print ( 'kid friendly word' ) |
12 | end |
13 | end ) |