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

How can I detect multiple keys pressed at the same time?

I am creating a driving game that requires movement at all times. However, I don't understand why, in this script, only one button press is registering at a time. For example, when I hold W and then A simultaneously, the car stops moving forwards and turns left.

function onKeyDown(inputObject, gameProcessedEvent)
	if inputObject.KeyCode == Enum.KeyCode.W then
		turn.AngularVelocity = Vector3.new(0,0,0)
	end
	if inputObject.KeyCode == Enum.KeyCode.S then
		turn.AngularVelocity = Vector3.new(0,0,0)
	end
	if inputObject.KeyCode == Enum.KeyCode.A then
		turn.AngularVelocity = Vector3.new(0,0,0)
	end
	if inputObject.KeyCode == Enum.KeyCode.D then
			turn.AngularVelocity = Vector3.new(0,0,0)
	end
end
 
input.InputBegan:connect(onKeyUp)

1 answer

The event that you have hooked up to the function is the 'InputEnded' event, which fires when a key (or input medium) is finished with. They will register individually as that's how it's being programmed. To deal with multiple keys being pressed down, you'll have to use check if keys are pressed.

While I'm not sure as to how you're going to program this, you can use the following functions to your advantage: http://wiki.roblox.com/index.php?title=API:Class/UserInputService/GetKeysPressed

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

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

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

E.g. (out of your context) if you wanted to run a function whenever A and C are simultaneously pressed:

function AC()
	-- ...
end

function onKeyDown(...) -- these are just basic outlines, but you'll get the point
	if A is being pressed and input:IsKeyDown(the C key) then
		AC()
	elseif C is being pressed and input:IsKeyDown(the A key) then -- Yes, I know, not efficient but this is to demonstrate the kind of thing you could do
		AC()
	end
end

input.InputAdded:connect(onKeyDown)

Hope I've helped you in some way :)

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