Android Basic Game Cycle Example Analysis _android

Source: Internet
Author: User

This example describes the Android basic game cycle. Share to everyone for your reference. as follows:

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 the cycle begun long Timediff;   The time it is 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.lo
      Ckcanvas ();
        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_skip
          S) {//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 '//a inconsistent state
     if (canvas!= null) {   Surfaceholder.unlockcanvasandpost (canvas);

 }}//End finally}}

I hope this article will help you with your Android program.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.