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

Correct use of IsKeyDown()?

I'm trying to detect the w key being held down, with the IsKeyDown function. And I'm pretty sure I'm not going at this correctly. How can I detect so I can just print something?


UIS = game:GetService("UserInputService")

if UIS:IsKeyDown(Enum.KeyCode.W) then
	print("w")
end

2 answers

✓ Accepted answer

You're using it correctly.

The problem is that the script runs this code once at the start of the game.

You could use a while loop to fix this,

local UIS = game:GetService("UserInputService")
while wait() do
	if UIS:IsKeyDown(Enum.KeyCode.W) then
		print("w")
	end
end

But a better solution would be to use InputBegan.

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.W then
		print("w")
	end
end)

This behaves differently than you may like, however, as it only prints once every time you press the W key, and it does not continue printing.

You could fix this by moving the while loop inside of the new function,

local UIS = game:GetService("UserInputService")

UIS.InputBegan:Connect(function(input)
	if input.KeyCode == Enum.KeyCode.W then
		while wait() do
			if UIS:IsKeyDown(Enum.KeyCode.W) then
				print("w")
			else
				break; -- Breaks the loop
			end
		end
	end
end)

If you have any further questions let me know.

Thank you.

1 comment

0

just what i needed

It works fine for me. Are you sure it's in a local script?

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