Timers几乎在所有的游戏中被使用,只是使用的种类不同.Timers是游戏的一个很重要的组成部分.Timers主要是用来控制游戏中事件的发生,比如周期性的事件等等.Timers的精确性比较低,但是也足够用的了.系统内核有一个周期性的Timer,精确到六十四分之一秒,而模拟器中的Timer精确到十分之一秒.使用UserHal::TickPeriod获得当前Timer的值.Symbian里面定义了三种Timer的概念:
1.简单Timer:用RTimer定义,主要负责在规定的明确时间以后触发事件或在准确的时间到来后触发事件.他是最低级的Timer,触发往往要用到活动对象,所以经常在活动对象中使用.当游戏引擎使用活动对象操作时,这种Timer很有用.
2.周期性Timer:CPeriodic,周期性的执行一个事件.当这种Timer被创建以后,相关的事件会被通过TCallBack进行回调.
3.心跳Timer:新鲜名次,嘎嘎.类似于周期性Timer,但是他是当计时器事件执行失败时候被回调,CPeriodic计时器不能准确处理一个事件,他是在处理失败的时候被回调,数次执行,直到执行成功.MBeating::Synchronize来通知执行错误.
在Symbian游戏里,我们不需要知道精确的事件,我们只要知道事件发生后经历了多久就OK了.而且,周期性的Timer常被用于游戏设计中,用这个Timer已经足够了.实例程序 代码规范还是很严格的)
以下内容为程序代码:
// Starts the timer
void CMyGameView::StartTimerL()
{
// tickInterval in microseconds; 100000 equals to 1/10 seconds const TInt KTickInterval = 100000;
iPeriodic = CPeriodic::NewL(CActive::EPriorityLow);
iPeriodic->Start(KTickInterval,
KTickInterval,TCallBack(Tick, this));
}
// Stops the timer
void CMyGameView::StopTimer()
{
iPeriodic->Cancel();
delete iPeriodic;
iPeriodic = NULL;
}
// Called by the timer when given interval elapsed
// This must be static method
TInt CMyGameView::Tick(TAny* aObject)
{ // call non-static method
((CMyGameEngine*)aObject)->NextTick();
// Allow the timer to continue it?s work return 1; }
// non-static timer event; called by static Tick()
void CMyGameView::NextTick()
{
TTime currentTime;
currentTime.HomeTime();
TInt64 currentTick = currentTime.Int64();
// Calculate elapsed time from last timer event in microseconds
// iLastTick is the current time from previous timer event
TInt64 frameTime = currentTick - iLastTick;
iLastTick = currentTick;
// Update activity on the screen according to frameTime
switch(iGameState)
{
case EPlayingTheGame:
// Calculate e.g. sprite positions in game screen and
// redraw the screen
HandleGameTick(frameTime);
break;
case EWatchingTheIntro:
// Intro of the game can be handled with the same timer
HandleIntroTick(frameTime);
break;
// Other possible game states could be handled too
}
}
| | 尽量避免在一个逻辑中使用多个Timer,以免参咱不清.除了RTimer,其他一些形式的Timer也需要活动对象.而且Timer的执行时间不能太短,一个周期里面的执行内容不要太多.以免发生混乱,而影响程序执行.
|