Dan*_*eny 6 iphone iphone-sdk-3.0 quartz-2d
我是iPhone开发人员的新手,但他正在尝试构建一个2D游戏.我正在关注一本书,但它创建的游戏循环基本上说:
function gameLoop
update()
render()
sleep(1/30th second)
gameLoop
Run Code Online (Sandbox Code Playgroud)
原因是这将以30fps运行.然而,这似乎有点精神,因为如果我的框架花了1/30秒,那么它将以15fps运行(因为它将花费尽可能多的时间来更新).
所以,我做了一些挖掘,发现了CADisplayLink类,它将我的gameLoop函数的调用与刷新率(或其中的一小部分)同步.我找不到它的很多样本,所以我在这里发布代码审查:-)它似乎按预期工作,它包括将经过的(帧)时间传递到Update方法,所以我的逻辑可以是帧率 - 独立(但我实际上无法在文档中找到CADisplayLink如果我的框架花费超过其允许的运行时间将会做什么 - 我希望它只是尽力赶上,并且不会崩溃!).
//
// GameAppDelegate.m
//
// Created by Danny Tuppeny on 10/03/2010.
// Copyright Danny Tuppeny 2010. All rights reserved.
//
#import "GameAppDelegate.h"
#import "GameViewController.h"
#import "GameStates/gsSplash.h"
@implementation GameAppDelegate
@synthesize window;
@synthesize viewController;
- (void) applicationDidFinishLaunching:(UIApplication *)application
{
// Create an instance of the first GameState (Splash Screen)
[self doStateChange:[gsSplash class]];
// Set up the game loop
displayLink = [CADisplayLink displayLinkWithTarget:self selector:@selector(gameLoop)];
[displayLink setFrameInterval:2];
[displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];
}
- (void) gameLoop
{
// Calculate how long has passed since the previous frame
CFTimeInterval currentFrameTime = [displayLink timestamp];
CFTimeInterval elapsed = 0;
// For the first frame, we want to pass 0 (since we haven't elapsed any time), so only
// calculate this in the case where we're not the first frame
if (lastFrameTime != 0)
{
elapsed = currentFrameTime - lastFrameTime;
}
// Keep track of this frames time (so we can calculate this next time)
lastFrameTime = currentFrameTime;
NSLog([NSString stringWithFormat:@"%f", elapsed]);
// Call update, passing the elapsed time in
[((GameState*)viewController.view) Update:elapsed];
}
- (void) doStateChange:(Class)state
{
// Remove the previous GameState
if (viewController.view != nil)
{
[viewController.view removeFromSuperview];
[viewController.view release];
}
// Create the new GameState
viewController.view = [[state alloc] initWithFrame:CGRectMake(0, 0, IPHONE_WIDTH, IPHONE_HEIGHT) andManager:self];
// Now set as visible
[window addSubview:viewController.view];
[window makeKeyAndVisible];
}
- (void) dealloc
{
[viewController release];
[window release];
[super dealloc];
}
@end
Run Code Online (Sandbox Code Playgroud)
对于任何反馈,我们都表示感谢 :-)
PS.如果你可以告诉我为什么所有的书都使用"viewController.view",但其他一切似乎都使用"[object name]"格式.为什么不[viewController视图]?
您在问题中将 Cocos2D 列为标签,但实际上并未使用任何 Cocos2D 代码。您是否考虑过为您的游戏实现 Cocos2D?这将为您省去一些不必要的麻烦。
至于您的语法问题[myObject view]用于调用方法,而myObject用于myObject.view设置/获取作为属性公开的实例变量。我不记得您是否[myObject view]也可以使用检索实例变量,但如果这有效,那么我想两者之间的唯一区别是语法,您可以使用这两种方法来检索实例变量。
希望其中的一些漫谈对您有用。
| 归档时间: |
|
| 查看次数: |
3246 次 |
| 最近记录: |