当前位置: 移动技术网 > IT编程>移动开发>Android > Android基本游戏循环实例分析

Android基本游戏循环实例分析

2019年07月24日  | 移动技术网IT编程  | 我要评论

七匹狼心水论坛,减肥愈加,坏蛋内传

本文实例讲述了android基本游戏循环。分享给大家供大家参考。具体如下:

// desired fps
private final static int  max_fps = 50;
// maximum number of frames to be skipped
private final static int  max_frame_skips = 5;
// the frame period
private final static int  frame_period = 1000 / max_fps; 
@override
public void run() {
  canvas canvas;
  log.d(tag, "starting game loop");
  long begintime;   // the time when the cycle begun
  long timediff;   // the time it took for the cycle to execute
  int sleeptime;   // ms to sleep (<0 if we're behind)
  int framesskipped; // number of frames being skipped 
  sleeptime = 0;
  while (running) {
    canvas = null;
    // try locking the canvas for exclusive pixel editing
    // in the surface
    try {
      canvas = this.surfaceholder.lockcanvas();
      synchronized (surfaceholder) {
        begintime = system.currenttimemillis();
        framesskipped = 0; // resetting the frames skipped
        // update game state
        this.gamepanel.update();
        // render state to the screen
        // draws the canvas on the panel
        this.gamepanel.render(canvas);
        // calculate how long did the cycle take
        timediff = system.currenttimemillis() - begintime;
        // calculate sleep time
        sleeptime = (int)(frame_period - timediff);
        if (sleeptime > 0) {
          // if sleeptime > 0 we're ok
          try {
            // send the thread to sleep for a short period
            // very useful for battery saving
            thread.sleep(sleeptime);
          } catch (interruptedexception e) {}
        }
        while (sleeptime < 0 && framesskipped < max_frame_skips) {
          // we need to catch up
          // update without rendering
          this.gamepanel.update();
          // add frame period to check if in next frame
          sleeptime += frame_period;
          framesskipped++;
        }
      }
    } finally {
      // in case of an exception the surface is not left in
      // an inconsistent state
      if (canvas != null) {
        surfaceholder.unlockcanvasandpost(canvas);
      }
    }  // end finally
  }
}

希望本文所述对大家的android程序设计有所帮助。

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网