我傾向於使用CADisplayLink在框架請求中觸發新框架和簡單時間計算,以確定我的邏輯有多遠。
假設您有一個NSTimeInterval類型的成員變量timeOfLastDraw。你希望你的邏輯在每秒60次跳動時打勾。然後(用一大堆變量使代碼更清晰):
- (void)displayLinkDidTick
{
// get the time now
NSTimeInterval timeNow = [NSDate timeIntervalSinceReferenceDate];
// work out how many quantums (rounded down to the nearest integer) of
// time have elapsed since last we drew
NSTimeInterval timeSinceLastDraw = timeNow - timeOfLastDraw;
NSTimeInterval desiredBeatsPerSecond = 60.0;
NSTimeInterval desiredTimeInterval = 1.0/desiredBeatsPerSecond;
NSUInteger numberOfTicks = (NSUInteger)(timeSinceLastDraw/desiredTimeInterval);
if(numberOfTicks > 8)
{
// if we're more than 8 ticks behind then just do 8 and catch up
// instantly to the correct time
numberOfTicks = 8;
timeOfLastDraw = timeNow;
}
else
{
// otherwise, advance timeOfLastDraw according to the number of quantums
// we're about to apply. Don't update it all the way to now, or we'll lose
// part quantums
timeOfLastDraw += numberOfTicks * desiredTimeInterval;
}
// do the number of updates
while(numberOfTicks--)
[self updateLogic];
// and draw
[self draw];
}
在你的情況中,updateLogic將應用固定的旋轉量。如果不斷旋轉,真是你想要的,那麼你可以僅僅通過numberOfTicks乘旋轉不變,甚至跳過這個整體方法,並做一些事情,如:
glRotatef([NSDate timeIntervalSinceReferenceData] * rotationsPerSecond, 0, 0, 1);
,而不是對你自己的變量。除了最微不足道的情況之外,你通常都想在每個時間範圍內完成一大堆複雜的事情。