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

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

Asked by 6 years ago
Edited 6 years ago

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

Log in to vote
1
Answered by 6 years ago

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 :)

Ad

Answer this question