Android基本游戏循环实例分析
本文实例讲述了Android基本游戏循环。分享给大家供大家参考。具体如下:
//desiredfps privatefinalstaticintMAX_FPS=50; //maximumnumberofframestobeskipped privatefinalstaticintMAX_FRAME_SKIPS=5; //theframeperiod privatefinalstaticintFRAME_PERIOD=1000/MAX_FPS; @Override publicvoidrun(){ Canvascanvas; Log.d(TAG,"Startinggameloop"); longbeginTime;//thetimewhenthecyclebegun longtimeDiff;//thetimeittookforthecycletoexecute intsleepTime;//mstosleep(<0ifwe'rebehind) intframesSkipped;//numberofframesbeingskipped sleepTime=0; while(running){ canvas=null; //trylockingthecanvasforexclusivepixelediting //inthesurface try{ canvas=this.surfaceHolder.lockCanvas(); synchronized(surfaceHolder){ beginTime=System.currentTimeMillis(); framesSkipped=0;//resettingtheframesskipped //updategamestate this.gamePanel.update(); //renderstatetothescreen //drawsthecanvasonthepanel this.gamePanel.render(canvas); //calculatehowlongdidthecycletake timeDiff=System.currentTimeMillis()-beginTime; //calculatesleeptime sleepTime=(int)(FRAME_PERIOD-timeDiff); if(sleepTime>0){ //ifsleepTime>0we'reOK try{ //sendthethreadtosleepforashortperiod //veryusefulforbatterysaving Thread.sleep(sleepTime); }catch(InterruptedExceptione){} } while(sleepTime<0&&framesSkipped<MAX_FRAME_SKIPS){ //weneedtocatchup //updatewithoutrendering this.gamePanel.update(); //addframeperiodtocheckifinnextframe sleepTime+=FRAME_PERIOD; framesSkipped++; } } }finally{ //incaseofanexceptionthesurfaceisnotleftin //aninconsistentstate if(canvas!=null){ surfaceHolder.unlockCanvasAndPost(canvas); } }//endfinally } }
希望本文所述对大家的Android程序设计有所帮助。