Handling key combinations (SOLVED)

Is there any way to handle multiple keys being pressed at the same time? e.g. if up and left are pressed at the same time, rotate sprite 45 degrees. Thanks in advance

Yes, you will get one separate action for each key so you can absolutely respond to that.

How would you handle it? would you use: if action_id == hash("left") and action_id == hash("up") thenor something else?

EDIT: Sorry, you can’t do that since each button will cause a separate call to on_input(). So action_id can’t be more than one value at a time.

One way is to have several if:s and allow more than one to be true. Either save state or modify a direction value.

Could you give me an example of this please?

Here’s one approach (untested):

if action_id == hash("up") then
    motion_vertical = -1
elseif action_id == hash("left") then
    motion_horizontal = -1
elseif action_id == hash("down") then
    motion_vertical = 1
    ...

Then consider both vertical and horizontal movement in update() and set both motions to 0 at the end of update().

That is what i am using at the moment. However, I can’t think of a way to make that work with a sprite to make it move diagonally since up and left are already 2 separate directions.
EDIT: I think I may have found a way to do this through saving the previous action into a variable then adding a condition to test whether the current action id and the last action id = up and left. This isn’t efficient but should do the job

Diagonally is the same as horizontal + vertical:

local motion_direction = vmath.vector3(motion_horizontal, motion_vertical, 0)

Or just add motion_horizontal to position.x and motion_vertical to position.y:

local position = go.get_position()
position.x = position.x + motion_horizontal
position.y = position.y + motion_vertical

The former example is easier to work with since you can scale the motion vector in one operation, multiply with dt to compensate for framerate and then just add to position.

To be honest, its working as it is so I may just leave it

1 Like

Yeah, your solution works too.

For my lowrezinvaders jam game I wrote a Lua module to simplify how you detect and react to multiple key presses. It work by forwarding on_input() calls to the module which will keep a map of all currently pressed keys. You can then query if a certain key is pressed and react to it. Example of how it’s used in the game.

3 Likes