clock负责提供一个真实时间和一个虚拟时间,真实时间从0开始按ms递增,和硬件时钟是同步的;虚拟时间也从0开始按ms递增,但不一定和真实时间同步。
要获得系统时间可以用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
闽公网安备 35060202000074号