代码之家  ›  专栏  ›  技术社区  ›  Snhp9

为什么我不能加两个双打

  •  0
  • Snhp9  · 技术社区  · 9 年前

    所以我在用唾沫做一个简单的游戏。但我在滴答声/渲染循环中遇到了一些问题。

    我需要它以每秒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
    

    下面是一段代码。如果你需要更多,请告诉我。

    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();
            }
    
        }
    }
    
    2 回复  |  直到 9 年前
        1
  •  2
  •   ilinca    9 年前

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

    浮动f=(浮动)0.2; 双d=2;

    f+=d=>2 d+=f=>2.2

        2
  •  0
  •   Eamonn O'Brien-Strain    9 年前

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

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

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

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