我的这辆车看起来像一个可以射击子弹的盒子。如果我按住或按住2或3个键,它们都可以正常工作,但是一旦我释放1个键,其他所有键都会停止,就像所有键都被释放一样。但是,如果我按任意键或再次按住任何键,所有按键仍然可以重新开始工作。
我搜索并找到了一个与我完全相同的问题,并通过循环run()方法(在我的情况下为moveCar()方法)解决了问题,但我不确定如何run()方法可以在这里循环。
我刚刚开始学习java,只是为了练习这个练习,因为我经历了摇摆篇章,没有制作游戏或任何严肃的东西,所以只想知道这不起作用的原因以及如何使它工作
public class MovingObject extends JFrame {
private BoxCar boxCar = new BoxCar();
private final int NUMKEYS = 5;
private boolean [] keys = new boolean [NUMKEYS];
public MovingObject() {
add(boxCar);
boxCar.addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
keys[0] = true;
break;
case KeyEvent.VK_RIGHT:
keys[1] = true;
break;
case KeyEvent.VK_UP:
keys[2] = true;
break;
case KeyEvent.VK_DOWN:
keys[3] = true;
break;
case KeyEvent.VK_A:
keys[4] = true;
break;
}
moveCar();
}
public void keyReleased(KeyEvent e) {
switch(e.getKeyCode()) {
case KeyEvent.VK_LEFT:
keys[0] = false;
break;
case KeyEvent.VK_RIGHT:
keys[1] = false;
break;
case KeyEvent.VK_UP:
keys[2] = false;
break;
case KeyEvent.VK_DOWN:
keys[3] = false;
break;
case KeyEvent.VK_A:
keys[4] = false;
break;
}
moveCar();
}
});
boxCar.setFocusable(true);
}
private void moveCar() {
if(keys[0]) {
if(boxCar.getXCoordinate() > 20)
boxCar.setXCoordinate(boxCar.getXCoordinate() - 20);
}
if(keys[1]) {
if(boxCar.getXCoordinate() < (boxCar.getWidth() - boxCar.getCarWidth() - 20))
boxCar.setXCoordinate(boxCar.getXCoordinate() + 20);
}
if(keys[2]) {
if(boxCar.getYCoordinate() > 20)
boxCar.setYCoordinate(boxCar.getYCoordinate() - 20);
}
if(keys[3]) {
if(boxCar.getYCoordinate() < (boxCar.getHeight() - boxCar.getCarHeight() - boxCar.getTireDiameter() - 20))
boxCar.setYCoordinate(boxCar.getYCoordinate() + 20);
}
if(keys[4]) {
boxCar.setBullet();
boxCar.setGun(true);
Timer timer = new Timer(100, new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(boxCar.bulletDistanceTravel() > boxCar.getWidth()) {
boxCar.setGun(false);
}
boxCar.repaint();
}
});
timer.start();
}
}
另一个问题是有时候子弹的速度是恒定的,但大部分时间,子弹的速度在每次射击时翻倍?