Android基本游戲循環(huán)實(shí)例分析
更新時間:2015年10月10日 12:09:49 作者:紅薯
這篇文章主要介紹了Android基本游戲循環(huán),以完整實(shí)例形式較為詳細(xì)的分析了Android實(shí)現(xiàn)基本游戲循環(huán)的相關(guān)技巧,具有一定參考借鑒價值,需要的朋友可以參考下
本文實(shí)例講述了Android基本游戲循環(huán)。分享給大家供大家參考。具體如下:
// 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程序設(shè)計有所幫助。
您可能感興趣的文章:
- Unity3D游戲引擎實(shí)現(xiàn)在Android中打開WebView的實(shí)例
- Android 游戲引擎libgdx 資源加載進(jìn)度百分比顯示案例分析
- Android游戲開發(fā)學(xué)習(xí)②焰火綻放效果實(shí)現(xiàn)方法
- Android游戲開發(fā)學(xué)習(xí)①彈跳小球?qū)崿F(xiàn)方法
- Android實(shí)現(xiàn)完整游戲循環(huán)的方法
- Android游戲開發(fā)實(shí)踐之人物移動地圖的平滑滾動處理
- Android 游戲開發(fā)之Canvas畫布的介紹及方法
- 解析Android游戲中獲取電話狀態(tài)進(jìn)行游戲暫?;蚶^續(xù)的解決方法
- Android游戲開發(fā)學(xué)習(xí)之引擎用法實(shí)例詳解
相關(guān)文章
Android通過自定義ImageView控件實(shí)現(xiàn)圖片的縮放和拖動的實(shí)現(xiàn)代碼
通過自定義ImageView控件,在xml布局里面調(diào)用自定的組件實(shí)現(xiàn)圖片的縮放。下面給大家分享實(shí)現(xiàn)代碼,感興趣的朋友一起看看吧2016-10-10