i wanna know how to detect if a key is being held down, like if the player is holding down the W key. Thanks
COMMUNITY QUESTION
how to know if a key is being hold down?
1 answer
Two events: InputBegan, and InputEnded. You can use these methods to detect when a key has been pressed and when a key has been lifted. I recommend storing these objects in a table so you can detect whenever ANY key is being held or is being lifted:
local UIS = game:GetService('UserInputService');
local pressedKeys = {};
UIS.InputBegan:Connect(function(Key, Processed)
if (Processed) then return nil end;
pressedKeys[Key.KeyCode.Name] = true;
end)
UIS.InputEnded:Connect(function(Key)
pressedKeys[Key.KeyCode.Name] = nil;
end);
With this, you can check if the key is currently being held by doing:
while pressedKeys["W"] do
wait();
print("W is being pressed.");
end
print("W is not being pressed anymore.");
3 comments
0
um quick question please, why do we need a table and a while loop? hehe sorry
0
"I recommend storing these objects in a table so you can detect whenever ANY key is being held or is being lifted." A while loop is how we detect if the key is being held down.
0
thanks!
This discussion is preserved as it was. New answers, comments, and votes are closed.

1 comment
UserInputService