Tuesday, November 24, 2009

Cocos2d Meets UIKit - you really can cross the beams

If you are getting started with Cocos2d, you are probably having a lot of fun. This is a great framework for developing games on the iPhone. But, you may find yourself wondering how to get more complex UI elements into your game. For example, you may want to collect some input from the user in a UITextField. Mixing UIKit and Cocos2d is possible! I have just scratched the surface so far, but I did come across a few articles that lead me in the right direction.

Below is a simple example of adding a UIKit Alert dialog and UITextField to a Cocos2d Scene. It turns out they play together quite well. The code below assumes you are in the "init" method of your Cocos2d Layer object. Normally, you would be adding Sprites, Labels, etc. here. But now, you want to add this dialog. Here is the code.....


- (id) init {
    self = [super init];
    if (self != nil) {

Sprite * bg = [Sprite spriteWithFile:@"blah.png"];
[bg setPosition:ccp(240, 160)];
[self addChild:bg z:0];

UIView* view = [[Director sharedDirector] openGLView];

NSString *score = [NSString stringWithFormat:@"You Scored: %d", gameScore];
UIAlertView* myAlertView = [[UIAlertView alloc] initWithTitle:score
                   message:@"High Score" delegate: self 
                   cancelButtonTitle: @"Cancel" otherButtonTitles: @"OK", nil];
[view addSubview: myAlertView];

CGAffineTransform myTransform = CGAffineTransformMakeTranslation(0.0, 75.0);
[myAlertView setTransform: myTransform];

nameField = [[UITextField alloc] initWithFrame
                         CGRectMake(12.0, 45.0, 260.0, 25.0)];
[nameField setBackgroundColor: [UIColor whiteColor]];
nameField.text = @"Enter Name Here"s
nameField.clearsOnBeginEditing = true;

[myAlertView addSubview: nameField];
[myAlertView show];
[myAlertView release];
    }
    return self;
}


As you can see, you can get a UIView from the Cocos2d Director. Once you have that, you have entered the UIKit world. The only other trick is the "Transform" that is used to make sure the geometry is compatible. This works great for my app. There is a lot more to learn about mixing UIKit and Cocos2d. I hope to learn more in the future!

1 comment: