views:

348

answers:

1

Hi

I'm new to Cocos2D but am having serious issues when trying to load a cocos scene in one of the UIViewControllers mixed with other normal UIKit UIViewControllers.

My project uses a UITabBarController to manage four view controllers. Three are normal UIKit view controllers while one of them I want to use cocos2D for (to draw some sprites and animate them).

The following is what I've done so far. In the applicationDidFinishLaunching method, I initialize cocos2D to use the window and take the first tabbarcontroller view:

- (void)applicationDidFinishLaunching:(UIApplication *)application {
  if( ! [CCDirector setDirectorType:CCDirectorTypeDisplayLink] ) {
    [CCDirector setDirectorType:CCDirectorTypeDefault];
  }

  [[CCDirector sharedDirector] setPixelFormat:kPixelFormatRGBA8888];
  [CCTexture2D setDefaultAlphaPixelFormat:kTexture2DPixelFormat_RGBA8888];
  [[CCDirector sharedDirector] setDisplayFPS:YES];

  [[CCDirector sharedDirector] attachInView: window];   

  [[[CCDirector sharedDirector] openGLView] addSubview: tabBarController.view];
  [window makeKeyAndVisible];  
}

Then in the third UIViewController code (where I want to use cocos2D) I do this (note: the view is being loaded from a NIB file which has a blank UIView and nothing else):\

- (void)viewDidLoad {
  [super viewDidLoad];

  // 'scene' is an autorelease object.
  CCScene *myScene = [CCScene node];

  // 'layer' is an autorelease object.
  MyLayer *myLayer = [MyLayer node];

  // add layer as a child to scene
  [myScene addChild: myLayer];

  [[CCDirector sharedDirector] runWithScene: myScene];  
}

However all I see is a blank white view and nothing else. If I call the following in viewdidLoad:

  [[CCDirector sharedDirector] attachInView: self.view];    

The app crashes complaining that CCDirector is already attached. Please help!

A: 

From what I can see it makes sense why the crash is happening. You have already called attachInView in applicationDidFinishLaunching and then you are trying to attach it again in viewDidLoad. Looking at your code there's a few things that don't really make sense to me.

If I understand your intention correctly you should only need to call attachInView in viewDidLoad but you could leave the CCDirector setup calls where they are inside applicationDidFinishLaunching

I initialize cocos2D to use the window and take the first tabbarcontroller view:

This part confuses me a bit. Where do you want the Cocos2D view to end up. Who do you want to child it to and do you want it to have any children views?

Rob Segal