1

所以,我正在尝试制作一个赛车程序。在这种情况下,我希望汽车减速直到速度为 0,因为用户释放了 W 键而不是完全停止。

这是代码:

JLabel carImage = new JLabel(new ImageIcon("carimage.jpg"));
int carAcceleration = 100;
int carPositionX = 0, carPositionY = 100;
// assume it is already add in the container

public void keyReleased(KeyEvent key) {
    handleKeyReleased(key);
}

int slowdown = 0;
Timer timer = new Timer(1000,this); // 1000ms for test
public void handleKeyReleased(KeyEvent key) {
    if(key.getKeyCode() == KeyEvent.VK_W) {
        slowdown=1;
        timer.start();
    }
}

public void actionPerformed(ActionEvent action) {
    if(slowdown == 1) {
        while(carAcceleration> 0) {
            carAcceleration--;
            carPositionX += carAcceleration;
            carImage.setBounds(carPositionX, carPositionY, 177,95);
            timer.restart();
        }
    }
    timer.stop();
    slowdown = 0;
}

但是,当我释放 W 键时。它等待了整整一秒钟,然后突然向右传送 100px 并停止。

我也尝试使用 Thread.sleep(1000); 但同样的事情也会发生。

JLabel carImage = new JLabel(new ImageIcon("carimage.jpg"));
int carAcceleration = 100;
int carPositionX = 0, carPositionY = 100;
// assume it is already add in the container

public void keyReleased(KeyEvent key) {
    handleKeyReleased(key);
}

public void handleKeyReleased(KeyEvent key) {
    if(key.getKeyCode() == KeyEvent.VK_W) {
        while(carAcceleration> 0) {
            carAcceleration--;
            carPositionX += carAcceleration;
            carImage.setBounds(carPositionX, carPositionY, 177,95);
            try {
                Thread.sleep(1000);
            } catch (InterruptedException ie) {
                //
            }
        }
    }
}

我希望它像这样执行。

carAcceleration | carPositionX  | Output    
----------------------------------------------------------------------
100             | 100           | carImage.setBounds(100,100,177,95);
                |               | PAUSES FOR SECONDS 
99              | 199           | carImage.setBounds(199,100,177,95);
                |               | PAUSES FOR SECONDS
98              | 297           | carImage.setBounds(297,100,177,95);
                |               | PAUSES FOR SECONDS
... and so on

提前致谢。:D

4

2 回答 2

2

示例使用阻尼弹簧模型来模拟这种减速。Ajavax.swing.Timer用于调整动画的速度。

图片

于 2013-08-05T17:38:53.263 回答
0

而不是carPositionX+=carAcceleration尝试carPositionY+=carAccleration。这应该使汽车在窗口坐标系的 y 轴上移动。

于 2013-08-05T12:27:52.647 回答