【问题标题】:Include cocos2d in non-cocos2d project在非 cocos2d 项目中包含 cocos2d
【发布时间】:2012-09-11 08:28:50
【问题描述】:
我进行了一些谷歌搜索和 stackoverflowing,但仍然存在该怎么做的问题。
我有一个用于 iphone 的大型导航项目 iOS5.1。
在几个 VC 上,我需要包含一些或多或少复杂的动画,比如男孩角色的咀嚼动画。
我使用过 cocos2d,我知道使用 cocos2d 很容易实现我的目标。但是是否有可能以某种方式将 coco2sd 的场景和图层包含到所需的 VC 中?或者以某种方式将视图与场景重叠?
任何提示将不胜感激。
【问题讨论】:
标签:
iphone
ios
animation
cocos2d-iphone
【解决方案1】:
我这样做的方式是在我初始化 ViewController 时创建一个 CCDirector,CCDirector 使用一个 OpenGL 视图,您可以创建一个 ViewController 的子视图。有了 CCDirector,你就可以做你通常在 Cocos2D 中做的所有事情了。
if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:kCCDirectorTypeMainLoop];
CCDirector *director = [CCDirector sharedDirector];
EAGLView *glview = [EAGLView viewWithFrame:CGRectMake(0, 0, self.view.frame.size.width,self.view.frame.size.height)];
[self.view insertSubview:glview atIndex:1];
[director setOpenGLView:glview];
【解决方案2】:
首先,你需要在你的 AppDelegate 中创建一个 director:
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// ...
// Create Cocos2D Director
//
// Try to use CADisplayLink director
// if it fails (SDK < 3.1) use the default director
if( ! [CCDirector setDirectorType:kCCDirectorTypeDisplayLink] )
[CCDirector setDirectorType:kCCDirectorTypeDefault];
CCDirector *director = [CCDirector sharedDirector];
}
然后在您的-viewDidLoad 方法中,将Cocos2D 创建的视图作为子视图添加到self.view:
- (void)viewDidLoad {
[super viewDidLoad];
// configre subviews
// ...
// Add your Cocos2D view
EAGLView * glView = [EAGLView viewWithFrame:self.view.bounds
pixelFormat:kEAGLColorFormatRGB565
depthFormat:0];
[glView setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight];
[[CCDirector sharedDirector] setOpenGLView:glView];
[self.view addSubview:glView];
// Run a blank scene for testing
CCScene * blankScene = [CCScene node];
[[CCDirector sharedDirector] runWithScene:blankScene];
}
然后您可以创建自己的场景来替换blankScene。
我强烈推荐你发一篇关于这项技术的帖子:"How To Integrate Cocos2D and UIKit"。我通过阅读@Ray 的帖子成功地实现了这一点! ;)