multiple key detection for KeyListener (java)

╄→尐↘猪︶ㄣ 提交于 2019-12-20 04:58:10

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!