我的 OpenGL ES 类和代码源自 Apple 的 GLES2Sample code sample .我使用它们来显示 3D 对象以我期望的恒定旋转速度围绕一个轴平稳旋转。目前,应用程序使用的帧间隔为 1,每次绘制 OpenGL View 时(在 EAGLView 的 drawView
方法中),我都会将模型旋转一定角度。
在实践中,这会产生不错的结果,但并不完美:在旋转过程中,当物体的大部分不在视线范围内时,渲染会变得更快,因此旋转不会具有恒定的角速度。我的问题是:如何让它更流畅?
尽管我欢迎所有建议,但我已经有了一个想法:每半秒测量一次渲染 FPS,并根据此调整每次重绘时的旋转角度。然而,这听起来不太好,所以:您如何看待这个问题,您将如何处理这个问题?
最佳答案
我倾向于使用 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);
而不是保留你自己的变量。尽管在最微不足道的情况下,您通常希望每个时间片做一大堆复杂的事情。
关于ios - 在 iPhone 上使用 CADisplayLink 在 OpenGL ES View 中进行恒速旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4114930/