简体   繁体   English

KeyListener的多键检测(java)

[英]multiple key detection for KeyListener (java)

How would one implement KeyListener so that I can create a two-player system where one person uses '.' 如何实现KeyListener以便我可以创建一个双人系统,其中一个人使用'。' 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. 我现在的方式是,当一个人按住箭头键时,他们的角色会移动,但是当你使用其他玩家的控制时,第一个人的角色会停止。

Create a HashMap<Int,Boolean> that marks which keys are currently pressed/depressed. 创建一个HashMap<Int,Boolean> ,用于标记当前按下/按下的键。

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;

From the sounds of things you're listening to a keyPressed event. 从您正在收听keyPressed事件的事物的声音。 Basically, you need to maintain stateful information about what keys are currently "down" and only stop the appropriate action when the keyReleased event occurs. 基本上,您需要维护有关当前“关闭”的键的有状态信息,并且仅在keyReleased事件发生时停止相应的操作。

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 您可能需要做的其他事情之一就是维护某些活动密钥的缓存...当我输入时,Ethan刚刚提到了这一点:P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM