欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  移动技术

Android基本游戏循环实例分析

程序员文章站 2023-12-01 20:01:52
本文实例讲述了android基本游戏循环。分享给大家供大家参考。具体如下: // desired fps private final static int m...

本文实例讲述了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程序设计有所帮助。