问题描述
我正在 iPhone 上编写游戏.我目前正在使用 NSTimer 来触发我的游戏更新/渲染.问题在于(在分析之后)我似乎在更新/渲染之间失去了很多时间,这似乎主要与我插入 NSTimer 的时间间隔有关.
I am programming a game on the iPhone. I am currently using NSTimer to trigger my game update/render. The problem with this is that (after profiling) I appear to lose a lot of time between updates/renders and this seems to be mostly to do with the time interval that I plug into NSTimer.
所以我的问题是使用 NSTimer 的最佳替代方法是什么?
So my question is what is the best alternative to using NSTimer?
请为每个答案选择一个.
One alternative per answer please.
推荐答案
你可以通过线程获得更好的性能,试试这样的:
You can get a better performance with threads, try something like this:
- (void) gameLoop
{
while (running)
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
[self renderFrame];
[pool release];
}
}
- (void) startLoop
{
running = YES;
#ifdef THREADED_ANIMATION
[NSThread detachNewThreadSelector:@selector(gameLoop)
toTarget:self withObject:nil];
#else
timer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60
target:self selector:@selector(renderFrame) userInfo:nil repeats:YES];
#endif
}
- (void) stopLoop
{
[timer invalidate];
running = NO;
}
在renderFrame
方法中,您准备帧缓冲区、绘制帧并将帧缓冲区呈现在屏幕上.(PS 有一篇很棒的文章介绍了各种类型的游戏循环及其优缺点.)
In the renderFrame
method You prepare the framebuffer, draw frame and present the framebuffer on screen. (P.S. There is a great article on various types of game loops and their pros and cons.)
这篇关于除了使用 NSTimer 之外,在 iPhone 上创建游戏循环的更好方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!