Dumoko
Dumoko

Reputation: 2644

Include cocos2d in non-cocos2d project

I did some googling and stackoverflowing, but still remained with the question what to do. I have a big navigation-based project, iOS5.1, for iphone. On couple of VCs i need to include some more or less complicated animations, like a chewing animation of a boy character. I've worked with cocos2d and i know it would be pretty easy to accomplish my goal with cocos2d. But is it possible to include somehow the scenes and layers with coco2sd into needed VC? Or somehow to overlap the view with s scene? Any hint would be highly appreciated.

Upvotes: 1

Views: 482

Answers (2)

Kjuly
Kjuly

Reputation: 35131

Firstly, you need to create a director in your AppDelegate:

- (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];
}

And in your -viewDidLoad method, add the view which is created by Cocos2D to self.view as a subview:

- (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];
}

You can create your own scene to replace the blankScene then.


I'd highly recommend you a post on this tech: "How To Integrate Cocos2D and UIKit". I implement this successfully by reading @Ray's post! ;)

Upvotes: 1

ggfela
ggfela

Reputation: 1152

The way I've done this is just creating a CCDirector when I init the ViewController, the CCDirector uses an OpenGL view that you make a subview of your ViewController. With the CCDirector in place you can do everything you would normally do in 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];

Upvotes: 2

Related Questions