【问题标题】:Why cant I add 2 doubles together为什么我不能将两个双打加在一起
【发布时间】:2015-03-06 05:16:53
【问题描述】:

所以我正在制作一个带有恶意的简单游戏。但是我在滴答/渲染循环方面遇到了一些问题。

我需要它以每秒 30 个滴答声运行。但 fps 需要尽可能快。

我遇到的问题是 while 循环没有运行

lastTime += msPerTick;

所以我的输出看起来像这样。没有添加。没有循环。没有渲染。

x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333
x:0.375 y:0.03333333333333333

这是代码的 sn-p。如果您需要更多,请告诉我。

public  static final int  TICKS_PER_SECOND = 30;
private static final int  MAX_TICKS_PER_FRAME = 10;
private boolean       running;
private Thread        thread;
private int           tickCount;
private int           frames;
private boolean       paused;

public void run() {
    init();
    float lastTime = (System.nanoTime() / 1000000) / 1000.0f;
    running = true;

    double msPerTick = 1.0 / TICKS_PER_SECOND;

    while (running) {
        synchronized (this) {
            float now = (System.nanoTime() / 1000000) / 1000.0f;
            int frameTicks = 0;
            while (now - lastTime > msPerTick) {
                System.out.println("x:" + (now - lastTime) + " y:" + msPerTick);

                if (!paused && frameTicks++ < MAX_TICKS_PER_FRAME) 
                    tick();


                lastTime += msPerTick; //<-- Issue here
            }

            if (!paused) {
                render((now - lastTime) / msPerTick);
            }
        }

        //Thread.yield(); No need for yield lets use sleep.
        try {
            Thread.sleep(paused ? 500 : 1);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

    }
}

【问题讨论】:

    标签: java render frame-rate


    【解决方案1】:

    因为您没有添加 2 个双打。如果您将 lastTime 的类型更改为双倍,则代码将正常工作。

    float f = (float) 0.2; 双 d = 2;

    f += d => 2.0 d += f => 2.2

    【讨论】:

    • 如果可以的话,我会给你一块饼干。好吧,这解释了一切。谢谢!
    【解决方案2】:

    我认为如果您的渲染操作花费的时间少于 1/30 秒,就会出现算法问题。

    当您启动外循环时,会在 1/30 秒内多次执行而不进入内循环。在 1/30 秒标记处,它恰好进入内循环一次,然后再花费 1/30 秒在外循环中循环。

    如果渲染时间超过 1/30 秒,那么您应该没有问题。

    你不能依赖 Thread.yield() 来做很多事情。

    【讨论】:

    • 但我陷入了内循环。不是外循环。我也将 yield 切换为 sleep。
    • 尝试将 print 语句放在外部循环中,看看它被调用的频率。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-01
    • 2022-01-07
    相关资源
    最近更新 更多