我將以下代碼用作簡單Android遊戲的遊戲循環。它工作得很好,但是偶爾會出現一場小小的呃逆。一切都凍結了一秒鐘,然後向前跳躍了一點,比它應該更遠。我在遊戲循環中進行了大量的閱讀,但是我仍然在實現平滑循環時遇到了一些問題。插值解決這個問題?我該如何去平滑運動?平滑Android遊戲循環
private final static int MAX_FPS = 30;
private final static int MAX_FRAME_SKIPS = 5;
private final static int FRAME_PERIOD = 1000/MAX_FPS;
protected Void doInBackground(Void... params) {
Log.d("MainTask", "starting game task");
Canvas canvas;
long begin; // the time when the cycle began
long delta; // the time it took for the cycle to execute
int sleep; // ms to sleep if ahead
int skipped; // number of frames being skipped
sleep = 0;
while (running) {
canvas = null;
try {
canvas = surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
begin = System.currentTimeMillis();
skipped = 0;
gamePanel.update();
gamePanel.draw(canvas);
delta = System.currentTimeMillis() - begin;
sleep = (int)(FRAME_PERIOD - delta);
if (sleep > 0) {
try {
Thread.sleep(sleep);
} catch(InterruptedException e) {}
}
while (sleep < 0 && skipped < MAX_FRAME_SKIPS) {
gamePanel.update();
sleep += FRAME_PERIOD;
skipped++;
}
}
} finally {
if (canvas != null) surfaceHolder.unlockCanvasAndPost(canvas);
}
}
Log.d("MainTask", "the task is complete");
return null;
}
參見:https://source.android.com/devices/graphics/architecture.html#loops – fadden