Cocos2D on the Mac – Part 1

Cocos2D is an excellent Objective-C framework for games, and hopefully you have heard or been looking at a certain Cocos2D book on Safari On-Line. Most of the tutorials out there are about running Cocos2D on iOS devices, but as of the last release, it now runs on the Mac too. In fact if your game does not have any UIKit views, porting it from iOS to the Mac becomes really simple. If you have been thinking about getting a Cocos2D game into the Mac AppStore, these series of blog posts should help you get there. With a simple 4 steps you will have a template that you should be able to start adding your game code to.

Step 1 – Getting the latest Cocos2D develop branch
Assuming you have Git installed on your Mac (if not, follow the steps here), in a folder of your choice run:

git clone git://github.com/cocos2d/cocos2d-iphone.git
git checkout develop

The last line is critical, you will want the develop branch with the latest changes to the Mac Xcode Template.

Step 2 – Installing the (new) Cocos2D Templates into Xcode
In the folder you just cloned the develop branch of Cocos2D, run:

sudo ./install-templates.sh

You are half way there, if you restart Xcode you should see the Cocos2D 1.0.0 templates.

Step 3 – Time to create the game shell and add Mr. Penguino
Select New Project in Xcode and choose the cocos2d-Application Mac template.

Give your Project a name, and set the Active Executable to your Project (and not the Cocos2D Libraries).

If you select your project under the Target Executable and click Build and Run you should see the Cocos2D HelloWorld on your Mac.

HelloWorld is always a good sign. This means you have Cocos2D working and running inside your Mac game. Lets add the Penguino, open up the HelloWorldScene.m class and in the init method add the lines:

// Add the Penguino
penguino = [CCSprite spriteWithFile:@"penguino1.png"];
[penguino setPosition:ccp(size.width/2,size.height/2)];
[self addChild:penguino];

Note that

CCSprite *penguino;

should be added as an instance variable in the HelloWordScene.h header file. You should also grab the Penguino1.png image from the Project link at the bottom of the post. This code does nothing more then add a standard Sprite on the middle of the screen.

Step 4 – Implementing Player Controls

Now you just need to implement the touch controls, or accelerometer, oh wait, we are on the Mac and not iOS. Lets go old school and move Penguino around using nothing more then the arrow keys.

Here once more Cocos2D makes it easy to respond to keyboard events.
Two sub-steps to respond to keyboard events.
First, in your layer init, declare that you want to receive the keyboard events, by using:

self.isKeyboardEnabled = YES;

Next you need to add either ccKeyDown, ccKeyUp, or both depending if you care to know when the user releases a particular key.

Lets add two methods above init, one to respond to the keyboard key down events, and another to move our penguin within the screen.

-(void)movePenguin:(CGPoint)directionOffset {
   CGSize size = [[CCDirector sharedDirector] winSize];
   CGPoint penguinPosition = [penguino position];
   float newXPosition = penguinPosition.x + directionOffset.x;
   float newYPosition = penguinPosition.y + directionOffset.y;

   if ((newXPosition < 0.0f) || (newYPosition < 0.0f)) {
     return; // Do not move
   }
   if ((newXPosition > size.width) || (newYPosition > size.height)) {
     return; // Do not move
   }

   [penguino setPosition:ccp(newXPosition,newYPosition)];
}

and the ccKeyDown method:

-(BOOL) ccKeyDown:(NSEvent *)event
{
   //NSLog(@"key down: %@", [event characters] );
   if ([event modifierFlags] & NSNumericPadKeyMask) { // arrow keys have this mask
      NSString *theArrow = [event charactersIgnoringModifiers];
      unichar keyChar = 0;
      if ( [theArrow length] == 0 )
         return YES;            // reject dead keys
      if ( [theArrow length] == 1 ) {
         keyChar = [theArrow characterAtIndex:0];
         if ( keyChar == NSLeftArrowFunctionKey ) {
            CCLOG(@"Left Arrow pressed");
            CGPoint movePosition = ccp(-1,0);
            [self movePenguin:movePosition];
            return YES;
         }
         if ( keyChar == NSRightArrowFunctionKey ) {
            CCLOG(@"Right Arrow pressed");
            CGPoint movePosition = ccp(1,0);
            [self movePenguin:movePosition];
            return YES;
         }
         if ( keyChar == NSUpArrowFunctionKey ) {
            CCLOG(@"Up Arrow Pressed");
            CGPoint movePosition = ccp(0,1);
            [self movePenguin:movePosition];
            return YES;
         }
         if ( keyChar == NSDownArrowFunctionKey ) {
            CGPoint movePosition = ccp(0,-1);
            [self movePenguin:movePosition];
            CCLOG(@"Down Arrow Pressed");
            return YES;
         }
      }
  }
  return NO;
}

The ccKeyDown method has a couple of interesting lines:

First we pull out the event string and ignore any of the modifiers like the Option key. Change this if you care to know if those keys are pressed.

NSString *theArrow = [event charactersIgnoringModifiers];

The second thing to note is we are ignoring every key except the arrow keys. You may want to allow for more keys then just the arrows, so adjust accordingly. Take a look at the EventsTest Target included with Cocos2D-Mac project (that you cloned in Step 1)

If you click build and run you should have Penguino on the center of the screen, and will be able to move him around with the arrow keys.

That’s it for this short Part 1 of getting your Cocos2D game on the Mac. You now have a shell of the game, with a moving Penguin based on the arrow keys. Next week, Box2D physics on the Mac, or if you have other topics/suggestions, let me know in the comments.

Cocos2DMacGame Source

Thanks for reading,
Rod

This post is part of iDevBlogADay, a group of indie iOS development blogs featuring at least two posts per day. You can keep up with your favorite developers through the iDevBlogADay web site, RSS feed, or Twitter.

UA-8095965-3