简体   繁体   English

Java游戏缓慢更新几秒钟

[英]Java game slow update for a few seconds

I'm making a game of life clone, (you know, just for fun) and I'm having a little problem with the update (tick) method. 我正在制作一个生命游戏克隆,(你知道,只是为了好玩)而且我对更新(tick)方法有点问题。

Here is the the update and render loop: 这是更新和渲染循环:

while (running) {
    double nsTick = 1000000000 / amountOfTicks;

    long now = System.nanoTime();
    deltaRender += (now - lastTime) / nsRender;
    deltaTick += (now - lastTime) / nsTick;
    lastTime = now;

    while (deltaRender >= 1){
        render();
        frames++;
        deltaRender--;

        if (tickRunning) {
            while(deltaTick >= 1) {
                tick();
                ticks++;
                deltaTick--;
            }
        }

        if (System.currentTimeMillis() - timer > 1000){
            timer += 1000;
            System.out.println("Ticks: " + ticks);
            frames = 0;
            ticks = 0;
        }
    }
}

stop();

As you can see I have separated the render and tick functions because tick's rate is controlled by the user in real time. 正如您所看到的,我将渲染和刻度函数分开,因为刻度的速率由用户实时控制。

The problem is that, when the game starts, (or is unpaused), tick has an unstable update rate for a few seconds (around 10) and then adjust to the right one. 问题在于,当游戏开始时(或未被暂停),tick会在几秒钟内(大约10秒)具有不稳定的更新速率,然后调整到正确的更新速率。 Can that be fixed? 可以修复吗?

The game currently runs on a single thread. 该游戏目前在单个线程上运行。

The problem appears to be that when you are pausing the game, you are still counting up the tick() s you have to execute (that is, deltaTick continues to increase); 问题似乎是当你暂停游戏时,你仍在计算你必须执行的tick() s(也就是说, deltaTick继续增加); and these piled up tick() s are than executed at once when the game is resumed. 并且当游戏恢复时,这些堆积的tick() s不会立即执行。 There are multiple solutions here; 这里有多种解决方案; one would be to pause increasing deltaTick , when the game is paused: 当游戏暂停时,一个是暂停增加deltaTick

if (tickRunning) {
    deltaTick += (now - lastTime) / nsTick;
}

Another approach would be to simply set deltaTick to 0 when you resume or start the game. 另一种方法是在恢复或开始游戏时简单地将deltaTick设置为0

Wait, i did something different that worked (maybe that's what you meant). 等等,我做了一些不同的工作(也许这就是你的意思)。 Here is the code: 这是代码:

while(deltaTick >= 1){
   deltaTick--;
   if(tickRunning){
       tick();
       ticks++;         
   }
}

The mouse is a little unresponsive, from time but i think that was there before. 从时间上看,鼠标有点反应迟钝,但我认为之前有过。 Thanks a lot! 非常感谢!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM