摆动动画暂停和恢复

时间:2014-06-14 23:44:02

标签: java swing animation game-loop

我希望增加暂停/恢复游戏的可能性。不幸的是我的解决方案只是暂停游戏,但没有恢复它(当我点击恢复按钮时没有任何反应 - 图像仍然存在)。我还尝试在thread上调用wait / notify方法,但它也没有用 - 我得到了Exception in thread "AWT-EventQueue-0" java.lang.IllegalMonitorStateException。暂停/恢复的最佳解决方案是什么?

游戏圈

public void run() {
    init();

    long startTime;
    long reTime;
    long waitTime;

    while (running) {
        startTime = System.nanoTime();
        int CarPosX = car.zwrocPolozenieX();
        int CarPosY = car.zwrocPolozenieY();
        update(b, CarPosX, CarPosY);
        render(b);
        //draw();
        repaint();


        if(b<4390) {
            b=b+szybkoscMapy;
        }

        reTime = System.nanoTime() - startTime;
        waitTime = targetTime - reTime/100000000;
        try {
            Thread.sleep(waitTime);
        }
        catch(Exception e) {

        }
    }
}

public void init() {
    if(thread == null) {
        thread = new Thread(this);
        thread.start();
    }
    b=0;
    running = true;
    image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
    g = (Graphics2D) image.getGraphics();


    map = new Map(levelNumber);
    car = new Car(map);
    car.setxpos(338);
    car.setypos(150);

}

监听

    pause_button.addActionListener( new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            bp.running = false;
        }
    });

resume_button.addActionListener( new ActionListener()
    {
        public void actionPerformed(ActionEvent e)
        {
            bp.running = true;
        }
    });

1 个答案:

答案 0 :(得分:4)

使用javax.swing.Timer来调整动画的速度。调查调用计时器的start()stop()方法的典型控件here。使用此类Timer的{​​{3}}也可能是感兴趣的。