java按空格键继续,Java KeyPressed-如果其他键也太旧,则无法检测是否按下了空格键...

As the title suggests, in my Java game, I cannot detect if I'm pressing the spacebar and other keys at the same time.

For example, spacebar is the shoot key, and the arrow keys make the player move. If I am pressing the up arrow key and the left arrow key and the spacebar, then it should shoot a bullet up and to the left.

However, after using multiple System.out.println(); to debug, I've found that if I am pressing two keys, it is not detecting the spacebar if it's pressed.

public void keyPressed(KeyEvent e) {

if(e.getKeyCode() == 32){

pressingSpacebar = true;

System.out.println("Spacebar pressed true");

}

// Up arrow key

if(e.getKeyCode() == 38){

up = true;

System.out.println("Up = true");

}

// Down arrow key

if(e.getKeyCode() == 40){

down = true;

System.out.println("Down = true");

}

// Right arrow key

if(e.getKeyCode() == 39){

right = true;

System.out.println("Right = true");

}

// Left arrow key

if(e.getKeyCode() == 37){

left = true;

System.out.println("Left = true");

}

}

Then in keyReleased:

public void keyReleased(KeyEvent e) {

if(e.getKeyCode() == 38){

up = false;

repaint();

}

if(e.getKeyCode() == 40){

down = false;

repaint();

}

if(e.getKeyCode() == 39){

right = false;

repaint();

}

if(e.getKeyCode() == 37){

left = false;

repaint();

}

if(e.getKeyCode() == 32){

pressingSpacebar = false;

}

}

This is how I am checking if you are pressing the spacebar and multiple keys:

if(pressingSpacebar){

if(right == true && down == true && up == false && left == false){

// Shoot bullet

}

}

Why isn't the spacebar being detected? If I don't check for spacebar being pressed the bullets shoot fine, but when I check for the spacebar it just doesn't detect it.

Note: I have read other posts similar to this question but the answers were not very helpful. I am a sorta newbie when it comes to this stuff so try to give a simple answer or explain it a bit. Thanks in advance!

解决方案

A KeyEvent is only generated for the last key pressed, so you need to keep track of a key when it is pressed (for example by adding it to a HashMap) and then on a keyReleased you need to remove the key from the HashMap.

The better way to do this is to use Key Bindings (not a KeyListener) to bind the KeyStroke to an Action.

Check out the KeyboardAnimation example found in Motion Using the Keyboard. It explains more about Key Bindings and provides a full working example of handling the Up/Down/Right/Left keys. In general any two keys can be held down at one time to give diagonal motion.

The logic will also work with 3 keys, but as has already been mentioned the keyboard itself may not support that many keys pressed at one time.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值