单独的JFrame打开时暂停游戏线程

时间:2014-05-14 20:38:20

标签: java multithreading jframe sleep

我在java中制作游戏,我正在尝试制作暂停菜单。目前我正在检查按下的esc按钮并运行我的菜单JFrame。问题是我的游戏一直在后台运行。菜单打开时如何暂停游戏线程?

主游戏循环代码

public void run() {
    try {
        init();
    } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    long lastTime = System.nanoTime();
    final double amountOfTicks = 60D;
    double ns = 1000000000/amountOfTicks;
    double delta = 0;

    while(running){
        long now = System.nanoTime();
        delta +=(now - lastTime)/ns;
        lastTime = now;
        if (delta >= 1) {
            tick();
            delta--;
        }
        render();
    }
    stop();
}

检查暂停菜单的代码

public void tick() {

    if (up) {

        playerUp = true;
        playerDown = false;
        playerLeft = false;
        playerRight = false;
        y -= SPEED;
        moving = true;
    }
    if (dn) {
        playerDown = true;
        playerLeft = false;
        playerRight = false;
        playerUp = false;
        y += SPEED;
        moving = true;
    }
    if (lt) {

        playerLeft = true;
        playerRight = false;
        playerDown = false;
        playerUp = false;
        x -= SPEED;
        moving = true;
    }
    if (rt) {
        playerRight = true;
        playerLeft = false;
        playerUp = false;
        playerDown = false;
        x += SPEED;
        moving = true;
    }


    if (esc) {
        pauseMenu.main(null);
    }

1 个答案:

答案 0 :(得分:0)

一些提示:

tick()是您运行游戏代码的地方,但它不应该决定何时进行勾选 - 因为如果它被暂停,它是如何取消暂停的呢?

您已经限制了拨打tick()的次数。从本质上讲,当你的游戏暂停时,你想要更加限制它。"