要獲得系統時間可以用System.currentTimeMillies(),系統硬件有一個計數器,當計算機啟動時,計數器從0開始每1ms加1,System.currentTimeMillies()返回從開機到現在經過的ms。我們不需要知道時分秒,只需要一個遞增的整數計時就可以了。
Clock改自Marshall "Game Programming Gems 3"中的C++代碼,主要成員變量:
thisTime:當前硬件時間,即System.currentTimeMillies()
systemTime:游戲的系統時間,即把thisTime轉換為從0遞增的時間
virtualTime:虛擬時間,從0遞增,但和真實時間不同步
代碼如下:
package game.engine.core; class Clock { // Clock是否運行: private boolean running; // 當前hardware clock: private int thisTime; // record the last hardware clock when calling stop(): private int lastTime; // systemTime從0開始遞增,和硬件時鐘同步: private int systemTime; // systemOffset就是硬件時鐘和systemTime的差: private int systemOffset; // 上一次停止的systemTime: private int pauseAt; // virtualTime starts from 0. private int virtualTime; // virtualOffset records how long the clock paused: private int virtualOffset; private int frameStart; private int frameEnd; private int frameCount; public Clock() { reset(); } // 重置Clock: public void reset() { running = false; // get the hardware clock: thisTime = (int)System.currentTimeMillis(); lastTime = thisTime; // and systemTime starts from 0: systemTime = 0; systemOffset = thisTime; pauseAt = 0; // init virtual time: virtualTime = 0; virtualOffset = 0; // init frame time: frameStart = 0; frameEnd = 0; frameCount = 0; } // 同步hardware clock: private void update() { lastTime = thisTime; thisTime = (int)System.currentTimeMillis(); // increase the systemTime: systemTime += (thisTime - lastTime); } // 啟動Clock: public void start() { if(!running) { running = true; update(); virtualOffset += (systemTime - pauseAt); System.out.println("[start]"); } } // 停止Clock: public void stop() { if(running) { running = false; update(); pauseAt = systemTime; System.out.println("[stop] at " + pauseAt); } } // Clock是否運行: pu