且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Java - KeyListener 多个按钮按下

更新时间:2023-12-03 20:08:46

同时按下多个键的情况变得奇怪的问题是,您在检查布尔值时使用了 if else.将 tick() 中的所有布尔检查分开以拥有单独的 ifs.如果任何一个按钮被持续按下,代码永远不会进入最后一个 else 块,在那里 VelX 和 VelY 被重置为零.

The problem why things are getting strange in multiple key presses together is that you are using if else's in checking the booleans. Separete all the boolean checks in tick() to own individual ifs. If any one of the buttons are being pressed constantly, the code never goes to the last else-block where VelX and VelY are reset to zero.

将tick方法中的代码改成这样:

Change the code in tick method to something like this:

//Set 'velocity' to zero first
game.p.setVelY(0);
game.p.setVelX(0);

if (left_key_down) {
    game.p.setVelX(-1);
} 
if (right_key_down) {
    game.p.setVelX(1);
} 
if (up_key_down) {
    game.p.setVelY(-1);
} 
if (down_key_down) {
    game.p.setVelY(1);
}