multiple key detection for KeyListener (java)

后端 未结 2 1512
时光取名叫无心
时光取名叫无心 2021-01-26 23:39

How would one implement KeyListener so that I can create a two-player system where one person uses \'.\' and \'/\' to control a character, and the other person can use the arrow

相关标签:
2条回答
  • 2021-01-26 23:55

    Create a HashMap<Int,Boolean> that marks which keys are currently pressed/depressed.

    Then in your game loop, you can move your objects depending on if the keys are depressed in this map.

    For example:

    if (keyMap.get(VK_COLON) == Boolean.TRUE) //True indicates pressed
       playerAXPos+= 10;
    
    0 讨论(0)
  • 2021-01-27 00:08

    From the sounds of things you're listening to a keyPressed event. Basically, you need to maintain stateful information about what keys are currently "down" and only stop the appropriate action when the keyReleased event occurs.

    This will require to have two seperate lines action handler, one for when the key is pressed and one when the key is released.

    One of the other things you might need to do is maintain some kind of cache of the active keys...which just got mentioned by Ethan as I was typing :P

    0 讨论(0)
提交回复
热议问题