问题
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 keys without them interrupting each other? The way I have it now is that when one person holds down the arrow key, their character moves, but the instant you use the other player's controls, the first person's character stops.
回答1:
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;
回答2:
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
来源:https://stackoverflow.com/questions/12170145/multiple-key-detection-for-keylistener-java