如果玩家 2 向另一个方向移动,则玩家 1 停止移动

player1 stops moving if player2 moves the other direction

如果我将播放器 1 和播放器 2 向上移动,假设我按下播放器 1 的向下键,我的播放器将停止向上移动。我找不到问题所在。有人可以帮我解释一下我做错了什么吗?

package game;

import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;

public class KeyInput extends KeyAdapter{

    private Handler handler;
    private boolean [] keyPressed = new boolean [4];

    public KeyInput(Handler handler){
        this.handler = handler;
    }
    public void keyPressed(KeyEvent e){
        int key = e.getKeyCode();

        keyPressed[0]= false;
        keyPressed[1]= false;
        keyPressed[2]= false;
        keyPressed[3]= false;

        for(int i = 0; i <handler.object.size(); i++){
            GameObject tempobject= handler.object.get(i);
            if (tempobject.getId()== ID.Player1){
                if (key == KeyEvent.VK_UP){tempobject.setSpeedy(-7); keyPressed[0] = true;}
                if (key == KeyEvent.VK_DOWN){tempobject.setSpeedy(7); keyPressed[1] = true;}
            }
            if(tempobject.getId()== ID.player2)
                if (key == KeyEvent.VK_W){tempobject.setSpeedy2(-7); keyPressed[2] = true;}
                if (key == KeyEvent.VK_S){tempobject.setSpeedy2(7); keyPressed[3] = true;}
        }
        if(key == KeyEvent.VK_ESCAPE)System.exit(1);
    }
    public void keyReleased(KeyEvent e){
        int key = e.getKeyCode();
        for(int i = 0; i <handler.object.size(); i++){
            GameObject tempobject= handler.object.get(i);
            if (tempobject.getId()== ID.Player1){
                if (key == KeyEvent.VK_UP) keyPressed[0] = false;
                if (key == KeyEvent.VK_DOWN) keyPressed[1] = false;

                if(!keyPressed[0] && !keyPressed[1])tempobject.setSpeedy(0);

            }
            if (tempobject.getId()== ID.player2){
                if (key == KeyEvent.VK_W) keyPressed[2] = false;
                if (key == KeyEvent.VK_S) keyPressed[3] = false;

                if(!keyPressed[2] && !keyPressed[3])tempobject.setSpeedy2(0);
            }
        }
    }
}

可能与此有关:

keyPressed[0]= false;
keyPressed[1]= false;
keyPressed[2]= false;
keyPressed[3]= false;

这样一来,无论何时按下任何键,其他键都会设置为 false,即使它们可能仍被按住。