本文介绍了Java主游戏循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写一个游戏循环,我在下面的示例中找到了代码这里.我还研究了其他方法来进行游戏循环,例如,本文.但是我无法让任何一个正常工作.所以我保留了第一个链接中的那个.

I am writing a game loop, I found the code in the example below here. I have also looked at other ways to do a game loop, such as from this article. I couldn't get any of those ones working though. So I kept with the one from the first link.

我想知道的事情:

  • 我编写游戏循环的方式是否是实现此目标的好方法?
    • 有什么建议吗?
    • Is the way I wrote my game loop a good way to do this?
      • Any suggestions?

      这是我当前的代码:

      public void run(){
          long lastLoopTime = System.nanoTime();
          final int TARGET_FPS = 60;
          final long OPTIMAL_TIME = 1000000000 / TARGET_FPS;
          long lastFpsTime = 0;
          while(true){
              long now = System.nanoTime();
              long updateLength = now - lastLoopTime;
              lastLoopTime = now;
              double delta = updateLength / ((double)OPTIMAL_TIME);
      
              lastFpsTime += updateLength;
              if(lastFpsTime >= 1000000000){
                  lastFpsTime = 0;
              }
      
              this.updateGame(delta);
      
              this.repaint();
      
              try{
                  Room.gameTime = (lastLoopTime - System.nanoTime() + OPTIMAL_TIME) / 1000000;
                  System.out.println(Room.gameTime);
                  Thread.sleep(Room.gameTime);
              }catch(Exception e){
              }
          }
      

      推荐答案

      最终,您需要转到类似 LWJGL的名称,但请允许我强调一下,请继续做您现在在这里所做的事情.它将教您基本知识.

      Eventually you'll want to move to something like LWJGL, but let me stress, keep doing what you're doing here for now. It will teach you fundamentals.

      做好你的循环.看起来不错,让我提供一些提示:

      Good job on your loop. Looks nice, let me offer a few pointers:

      • 重新绘制将不会立即渲染屏幕.它告诉 RepaintManager 在准备就绪时进行渲染.使用 paint . paintImmediately将阻止执行,直到重新绘制组件为止,以便您可以测量渲染时间.

      • Repaint will not render the screen immediately. It tells the RepaintManager to render when its ready. Use paintImmediately instead. paintImmediately will block execution until the component has been redrawn so you can measure rendering time.

      Thread.sleep通常具有几毫秒的漂移.您应该使用它来防止循环使用过多的CPU,但是请确保您了解睡眠10毫秒可能会睡眠5毫秒还是可能睡眠20毫秒.

      Thread.sleep typically has a few milliseconds drift. You should be using it to keep your loop from using too much CPU, but make sure you understand if you sleep 10 milliseconds you might sleep 5 milliseconds or you might sleep 20.

      最后:

      double delta = updateLength / ((double)OPTIMAL_TIME);
      

      如果updateLength小于OPTIMAL_TIME,请不要调用更新.换句话说,如果增量小于1,请不要更新. 本教程解释了为什么我比以前更好.

      If updateLength is less than OPTIMAL_TIME, don't call update. In other words, if delta is less than one, don't update. This tutorial explains why better than I ever could.

      这篇关于Java主游戏循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 06:27