如何在按下箭头键时使精灵移动一次?

时间:2019-01-21 18:33:43

标签: java sprite actionevent

我正在尝试使精灵停止连续移动。现在,该代码使子画面不停地沿用户通过箭头键指示的方向移动。我想按一个箭头键,使子画面沿该方向移动一次(仅10步)。

 public class Contents extends JPanel implements ActionListener, KeyListener {
Timer t = new Timer(100, this);
private Image man;
int x=0, y=0;

public Contents() {
    super.setDoubleBuffered(true);
    t.start();
    addKeyListener(this);
    setFocusable(true);
    setFocusTraversalKeysEnabled(false);
}

@Override
public void paintComponent (Graphics g) {
    super.paintComponent(g);
    super.setBackground(Color.white);
    ImageIcon ii = new ImageIcon("guy.png");
    man = ii.getImage();

    Graphics2D g2d = (Graphics2D)g;
    g2d.drawImage(man, x, y, this);
}

    double xv = 0;
    double yv = 0;

    public void move() {
        x += xv;
        y += yv;
    }
    public void up() {
        yv = -1;
        xv = 0;
    }
    public void down() {
        yv = 1;
        xv = 0;
    }
    public void left () {
        xv = -1;
        yv = 0;
    }
    public void right () {
    xv = 1;
    yv = 0;
    }
@Override
public void actionPerformed(ActionEvent e) {
    repaint();
    //Collision for left and right walls
    if (x==0) {
        xv = 1; 
    }
    else if (x==900-240) {
        xv = -1;
    }
    // Collision for top and bottom walls
    if (y==0) {
        yv = 1;
    }
    else if (y==600-320) {
        yv = -1;
    }
    move();
}
public void keyPressed(KeyEvent e) {
    int code = e.getKeyCode();
    if (code == KeyEvent.VK_UP) {
        up();
    }
    if (code == KeyEvent.VK_DOWN) {
        down();
    }
    if (code == KeyEvent.VK_LEFT) {
        left();
    }
    if (code == KeyEvent.VK_RIGHT) {
        right();
    }
}
public void keyTyped(KeyEvent e) {}
public void keyReleased(KeyEvent e) {}

}

当我删除ActionEvent下的边界时,它可以工作。边界可防止精灵离开屏幕。但是我也想保留边界并控制精灵。

1 个答案:

答案 0 :(得分:0)

我知道了。在keyReleased下,设置xv = 0。然后,当您释放箭头键时,精灵将停止移动。