Cocos 2D and Me

Writing Your First Cocos2d iPhone Code

by Ben on Mar.04, 2010, under Cocos2D, Code Samples

If you’re like me, you’re probably dying to jump in and start writing some code. We’re about to do just that. By the end of this tutorial, you’ll be able to display a background, graphics and some text. Certainly nothing we really need Cocos2d for, but the few things you’ll learn in this tutorial will form the basis for most of your future code, so it’s worth getting them right at the beginning. If you just want to see the code, jump to the end of the article for the link.

The first thing to do is to boot up Xcode and create a new Cocos2d for iPhone project. If you haven’t installed the templates yet, you can follow the directions here. Create a regular Cocos2d project from the template (not with Chipmunk or Box2d). Once this is done, go into the Classes folder and remove the HelloWorldScene files, we won’t be needing them.

We’re going to have three layers in this project, a background layer, a sprite layer and a text layer. So go ahead and add three new files to your project, and name them BackgroundLayer, SpriteLayer, and TextLayer. We’re also going to need a scene to hold these layers, so create a new file called GameScene. Of course, don’t forget to create the .h files as well. Once you’ve done all that, your project should look something like this:

Files

First we’re going to create our background layer. Open up BackgroundLayer.h, import the cocos2d headers, and make sure the object inherits from CCLayer. You may as well complete these steps in SpriteLayer.h and TextLayer.h as well. Your layer header files should now look like this

  1.  
  2. #import "cocos2d.h"
  3.  
  4. @interface BackgroundLayer : CCLayer {
  5.        
  6. }
  7.  
  8. @end
  9.  

We’re only going to write one method in the implementation files for now, which will be the init method. I’ll show the code first, and then we can go through it:

  1.  
  2. #import "BackgroundLayer.h"
  3.  
  4. @implementation BackgroundLayer
  5.  
  6. - (id) init
  7. {
  8.         self = [super init];
  9.         if (self != nil) {
  10.                 //load image file
  11.                 CCSprite *background = [CCSprite spriteWithFile:@"background.png"];
  12.                 //get the current screen dimensions
  13.                 CGSize size = [[CCDirector sharedDirector] winSize];
  14.                 //place the image in the center of the screen
  15.                 background.position = ccp(size.width/2, size.height/2);
  16.                 //add the sprite object to the layer
  17.                 [self addChild:background];
  18.         }
  19.         return self;
  20. }
  21.  
  22. @end

The code should be fairly self explanatory. Basically we are just loading an image file and placing it in the center of the layer. The only thing that might not be familiar is “ccp”, with is a Cocos2d method for creating a point. If you need a background image, you can find one here. Make sure you include the file in your project as you normally would.

Next we’ll implement the SpriteLayer. This is going to be very similar to the BackgroundLayer, except this time we will place the image off to the left of the screen. The X and Y axes in Cocos2d start from the bottom left corner, not the top left, where as sprites work from the center of the image. So by placing the image at position 150, 150, we are effectively saying “place the center of the image 150 pixels up from the bottom of the screen, and 150 pixels across from the left”. Once we’ve got the code up and running, change the position of the image a few times to get a better understanding of this. If you can’t manage to find your own image, here is the one we used.

  1.  
  2. #import "SpriteLayer.h"
  3.  
  4. @implementation SpriteLayer
  5.  
  6. - (id) init
  7. {
  8.         self = [super init];
  9.         if (self != nil) {
  10.                 //load image file
  11.                 CCSprite *robot = [CCSprite spriteWithFile:@"robot.png"];
  12.                 //place the image to the left of the screen
  13.                 CGSize size = [[CCDirector sharedDirector] winSize];
  14.                 robot.position = ccp(150, size.height/2);
  15.                 //add the sprite object to the layer
  16.                 [self addChild:robot];
  17.         }
  18.         return self;
  19. }
  20.  
  21. @end
  22.  

Next, we’ll create the last layer. Rather than showing an image this layer will display some text. If you’ve used UILabels at all, which I’m sure you have, then CCLabels will be look quite familiar. Here’s the implementation for the TextLayer:

  1.  
  2. #import "TextLayer.h"
  3.  
  4. @implementation TextLayer
  5.  
  6. - (id) init
  7. {
  8.         self = [super init];
  9.         if (self != nil) {
  10.                 CCLabel* myLabel = [CCLabel labelWithString:@"Dance Like A Robot" dimensions:CGSizeMake(100,100) alignment:UITextAlignmentCenter fontName:@"Arial" fontSize:30];
  11.                 CGSize size = [[CCDirector sharedDirector] winSize];
  12.                 myLabel.position = ccp(360, size.height/2);
  13.                 [self addChild:myLabel];
  14.         }
  15.         return self;
  16. }
  17.  
  18. @end
  19.  

Now that we’ve created our three layers, we can tie them together in our scene class. This is a fairly simple matter of adding each layer to the scene. Here’s the implementation, don’t forget to also import the cocos2d header files and inherit from the CCScene class in the GameScene.h file.

  1.  
  2. #import "cocos2d.h"
  3.  
  4. @interface GameScene : CCScene {
  5.  
  6. }
  7.  
  8. +(id)scene;
  9.  
  10. @end
  11.  
  1.  
  2. #import "GameScene.h"
  3. #import "BackgroundLayer.h"
  4. #import "SpriteLayer.h"
  5. #import "TextLayer.h"
  6.  
  7. @implementation GameScene
  8.  
  9. +(id)scene {
  10.         // ’scene’ is an autorelease object.
  11.         CCScene *scene = [CCScene node];
  12.        
  13.         // ‘layer’ is an autorelease object.
  14.         BackgroundLayer *backgroundLayer = [BackgroundLayer node];
  15.         SpriteLayer *spriteLayer = [SpriteLayer node];
  16.         TextLayer *textLayer = [TextLayer node];
  17.        
  18.         // add layers as a children of the scene
  19.         [scene addChild:backgroundLayer];
  20.         [scene addChild:spriteLayer];
  21.         [scene addChild:textLayer];
  22.        
  23.         // return the scene
  24.         return scene;
  25. }
  26.  
  27. @end
  28.  

As you can see, we simply create each of the layers and then add them as children to the scene. The order you add them in is important, so if you add the background last you won’t see the other two layers. One other thing you might be unsure of is the call to “node” when creating the layers. You can pretty much call “node” on any Cocos2d object and it will create a new instance of it. So if you call “node” on a CCLayer, it creates a new CCLayer. If you call “node” on a CCSprite, it returns a new CCSprite. Think of it as a bit like calling alloc/init on your normal Objective C objects.

Finally, to get everything up and running we need to modify the app delegate a bit. Change the imports so that we’re importing “GameScene.h” rather than “HelloWorldScene.h”, and then change the last line of the applicationDidFinishLaunching method accordingly. Note that we are telling the CCDirector that we want to start running with the GameScene. Later on we’ll learn how to set up a menu, and call different scenes at different times.

  1.  
  2. [[CCDirector sharedDirector] runWithScene: [GameScene scene]];
  3.  

You should now be able to build and run to see your beautiful creation. Once you’re done, play around with the positioning numbers a bit, or add some new sprites. You should now have the very basics of starting your Cocos2d project covered.

Simulator

For those who can’t get things working, here’s a copy of the project that includes everything we did in this tutorial.

Leave a Comment more...

Installing the Cocos2d iPhone Templates

by Ben on Feb.25, 2010, under Cocos2D

To get started writing Cocos2D code, the first thing you’ll want to do is install the Xcode templates. The templates are a great starting point for any Cocos2D project, particularly if you want to create projects using the Chipmunk or Box2d physics libraries.

First of all, make sure you have the latest release downloaded and stored somewhere suitable – I recommend in your iPhone projects folder. For reasons mentioned here, I recommend the latest unstable release (at least until v1.0 comes out).

To install the templates, you’ll want to open up the Terminal. If you’re not sure how to open up the Terminal, Spotlight is your friend. Just hit Command-Space, and type in Terminal. This is a great way to open apps or documents you don’t have quick access to, or are not sure where they are stored.

Spotlight

So, once the Terminal is open, navigate to where the Cocos2d project is stored. When you are inside the folder, all you need to run is

  1. ./install_template.sh

Terminal

Once the script has finished executing, open up Xcode and start a new project. You should now have three new templates in there to get started with. I suggest you make a new project for each type, and run them to see what happens. It’s a good idea to have a quick look around in the code as well to see how things work.

Xcode Templates

If for some reason you want to remove the templates, or remove an older version of the templates, you can find out where they are stored by viewing the “install_template.sh” file. Open it up in TextEdit, and have a look at the first few lines of the script – most likely they will mention this directory: “/Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Project Templates/Application/”. Navigate to that folder from the Finder, and remove any templates you no longer want.

1 Comment more...

Key Classes in Cocos2d

by Ben on Feb.15, 2010, under Cocos2D

There are a few classes in Cocos2d that you are likely to come across over and over again. Since you’ll be seeing them so frequently, getting to know them right away seems like a good place to start.

CCDirector – The CCDirector class is in charge of running the show. If you want to pause your game for some reason (eg. a phone call comes in), it’s as simple as telling the CCDirector to pause – and another one line call will allow you to resume your game exactly where it left off.

CCScene – In a typical game, as well as the gameplay itself, there are also high scores to view, settings to change, a tutorial to read, and so on. Cocos2D handles all the movements between these different parts of your game by representing each as a CCScene. So, you might have a GameScene, a HighScoresScene, a SettingsScene, and a TutorialScene. Cocos2D then allows you to transition between these scenes at the appropriate time with ease.

CCLayer – Each scene is usually made up of one or more layers. If we are in the GameScene, then you might have a BackgroundLayer which simply displays the background, a PlayerLayer which holds your spaceship or character, and an EnemiesLayer, which holds all of the things you’re trying to kill. This allows for a good object orientated design, and allows each layer to handle input, collisions, and so on, as appropriate.

CCSprite – A CCSprite represents a graphic object. This is what you’ll use to represent your game characters, weapons, enemies, and so on. CCSprite offers a very simple means to load in graphics, move them around and do all other sorts of things to them.

CCLabel – As you might expect, this class allows you to render text on screen.

CCNode – The CCNode class is the simplest object type in the game, which everything is derived from. If it’s drawn on screen, moves around, or contains things that are drawn on screen, then it’s a type of CCNode. CCScene is a CCNode, CCLayer is a CCNode, etc. Think of CCNode as bit like the NSObject of Cocos2d.

One thing to note is that v0.9 of Cocos2d introduced the CC namespace. This means that a lot of the examples you find on the net no longer work, but it’s a fairly simple fix – just prefix any of the Cocos2d class references with “CC”. If you’re after a little bit more on the key classes, have a read of this great introduction. Just remember that the article is a bit outdated, and doesn’t include the CC namespace.

1 Comment more...

Running the Cocos2d Demos

by Ben on Feb.06, 2010, under Cocos2D

The Cocos2d for iPhone Xcode project comes with a number of demos, which are useful both for seeing visually what the engine is capable of, and for digging into the code to see how things are done.

To start, download the latest version from the official Cocos2d for iPhone website. There are a few options for which package to download, but I recommend you get the latest Unstable Version. As Cocos2d is still in pre-release the API is in somewhat of a state of flux, and it often changes some between versions. In my experience the unstable versions have actually been perfectly stable, and have the benefit of including all the latest API changes, meaning you won’t need to mess around making changes to your code later on.

If you open up the downloaded archive, you’ll see an Xcode project inside:

Cocos2d Xcode project

As you can see, I’m currently running Cocos2d v0.99.0-rc – in other words the release candidate for v1.0. Open up the Xcode project and do a Build as a sanity check to make sure everything is ok. You might get some Warnings, but these can be safely ignored.

To run the demos, you’ll probably need to make a small change to your Xcode settings. Go to the View menu, and choose Customize Toolbar. From here, you want to drag both the Active Target and the Active Executable drop downs on to your toolbar, like so:
Xcode Customize Toolbar

You’ll then need to select the same thing for both the Active Target and the Active Executable, as in the image above. You might also need to change the Overview drop down so that the code runs on a version of the Simulator (or your Device, if you prefer).

At the moment there are about 40 demos you can run, so work your way through them to get a feel for the library.

Leave a Comment more...

Introduction to Cocos2D for iPhone

by Ben on Feb.04, 2010, under Cocos2D

Now that we’ve decided upon Cocos2D for our game engine, let’s take a look into what the engine offers. Before we get too much further in though, I’d like to recommend that if you are brand new to the iPhone platform and/or Xcode, I would highly advise that you do a little catch up reading. One of the best ways to do this is to read Beginning iPhone Development. This really is one of the best books around on how to get started developing on the iPhone, and gives a good coverage of what you can do with the platform.

Now that that’s out of the way, we can a look at what Cocos2D has to offer. If you take a look at the official Cocos2D for iPhone website, there is a quick summary in the About section of the main engine features. Let’s go over a few of them:

  • Scene management – just about all games have different screens apart from the main game. These might be high scores, settings, different levels, and so on. Cocos2D lets you set these up easily, and transition between them with a number of (sometimes cheesy) effects.
  • Sprites – a sprite is pretty much the technical name for a graphic or image. If your game includes any sort of graphics, generally they will be handled by the Sprite class in Cocos2D in a memory efficient manner.
  • Actions – Cocos2D allows you to run all sorts of actions on your sprites, such as movement, rotation and scaling.
  • Physics engine – Cocos2D integrates with two well established physics engines, Box2D and Chipmunk. Both engines allow you to easily implement complex physics interactions between objects and the game environment.
  • Menus – setting up your menus and controlling the flow between the different parts of your game couldn’t be much easier.

Naturally, Cocos2D offers many other things, but the points above are probably the main features you’ll be using, at least while we get started. While you’re looking at the About page on the official site, you might as well check out the videos as well. These show off some of the different effects that the engine is capable of.

Leave a Comment more...

Selecting an iPhone Games Engine

by Ben on Feb.01, 2010, under General Games Development

You may have heard the term “game engine” before, but never paid much attention to what it means. Game engines are generally libraries of code designed to do a lot of the hard work in creating a game. Most modern game engines are impressively comprehensive, and can include simple things like loading images and moving them around, to more complex ideas such as designing and laying out levels. There are already several game engines for the iPhone, and with all the conflicting information available online, selecting one is confusing at best. As you may have already guessed from the name/URL of this blog, I’ve already made my decision, but that doesn’t mean you’ve made yours. I also feel it’s important to know what else is out there, as a wise coder always knows what options they have, rather than how to do everything with one option.

Our Criteria

As this will be my first game, I’m going to stick with the KISS principle. Like many of you, if I make things too complicated for myself I’m going to lose heart and eventually give up. So, here’s a few points of what I’m after in a game engine, and what sort of game I want to develop:

  • I’ll be making a 2D game. Adding that third dimension adds a whole new layer of complexity, and I have no idea how to deal with 3D models. Flat images I can deal with.
  • I don’t want to create a puzzle game. This is simply a matter of choice, as I want to be excited by what I’m developing. Puzzle games are fun, but they don’t excite me.
  • I want to understand what I’m doing. So, I’m not looking for a super high level engine which allows me to do everything quickly, but is impossibly hard to tweak once I want to do anything unusual – which is bound to happen.
  • The engine I select needs a good support network. Whilst there are some really great libraries out there, without any documentation or support they’re going to have a very steep learning curve.

And that’s about it. Let’s move on at take a look at what I consider to be the main options available for an iPhone game engine.

Core Animation / Core Graphics

Core AnimationThe Core components included in the iPhone SDK are, believe it or not, capable of powering a game. If you do enough reading on this topic, you will find many people who tell you you are wasting your time by developing a game using only the standard libraries, and to some extent this is true. As the standard Core libraries aren’t really built for developing games, they do have limitations. If your game is a simple puzzle type game where only one or two things are moving onscreen at a time, the Core libraries can be a good choice. They’re built-in, they’re free, and they’re using the language you are probably already used to, Objective-C, so there’s not much of a learning curve. There’s also going to be plenty of Apple documentation and support. The downside is that performance is going to be a problem if you start to do anything complicated. There’s a good example of developing a game using the Core libraries here.

OpenGL

OpenGLOpenGL is pretty much the standard games engine for a large number of platforms, including the iPhone. It is incredibly powerful, well supported, and used in a huge number of modern games. Unfortunately, OpenGL is a pure C framework that it is not particularly intuitive, particularly for a beginner. It has been around for a very long time, and as such can feel archaic and bloated – many lines of code are required just to display a simple graphic onscreen. For those willing to invest the time and dedication, OpenGL can be a fantastic platform, but for my purposes I believe it is not a good choice. There are other libraries around which use the power of OpenGL, but provide a higher level development experience.

Torque

Torque 2D for iPhone has been developed by the well known company GarageGames. Torque has been released for many different platforms, and as such has a long solid history and is quite a popular choice. If you are planning on building a 2D game, Torque would be a good choice. It offers a visual game builder, and includes the full source with the package in case you want to make any modifications yourself. Torque also provides an easy way to port your games to other platforms, such as Xbox360 or Wii. The main reason I personally would not use Torque at this time is that I feel there’s too much of a learning curve. Torque uses it’s own scripting language, so you won’t be coding in Objective-C, and having never had any experience with game builders such as this I fear I am too far out of my depth. I don’t feel comfortable building everything with drag and drop and scripts, I want to write some actual code! Other downsides include the cost, and needing to have a “developed with Torque” splash screen displayed when launching your game (if using the indie version). However, if you think scripting and drag-and-drop appeals to you, it might be worth giving one of the demos a try, though from memory there’s no specific iPhone Torque demo available.

Unity

UnityUnity is another drag and drop type game builder, and as such is seen as a direct competitor to Torque. Unlike Torque 2D, Unity supports both 2D and 3D games (Torque 3D for iPhone is coming though, sometime). The advantage of this is obvious, providing more flexibility in the type of games you can create. Unity also provides scripting features, but this time in C# and Javascript, so is more likely to appeal to more people. Unity reportedly also has much better documentation and support than Torque, so if I were to choose a visual game editor such as this, Unity would probably be my choice. The main reason I have not chosen Unity is that it is really a 3D game engine. Whilst 2D games certainly can be built with it, I believe this will add another layer of complexity which I just don’t need. Unity also has costs associated with it, and has the same splashscreen requirement for the cheaper version. If you do decide Unity is down your alley, there should be a demo for the iPhone available, and a great set of tutorials to get you started here.

Cocos2D

So, finally we get to Cocos2d for iPhone. Cocos2d is an open source framework built specifically for creating 2D games, which has been ported to iPhone. It has some really nice effects which you can see in the video demos, and gets some great reviews for people who are using it. All code is written in Xcode in regular Objective-C, so anyone who has done some iPhone development already should feel comfortable with the syntax at least. The catch is that documentation is sorely lacking. After a few hours of searching I only managed to come up with a small collection of articles, half of which are already out of date, so there is more of a learning curve than I was hoping for.

The Winner – Cocos2D

So, obviously I’ve chosen to go with Cocos2d, but why? Well, it fills most of my criteria. It’s specifically for 2D, so we’re keeping things simple – I don’t picture myself working on 3D games anytime soon, and I expect when I do it will be as large a jump from 2D games to 3D games, as it will be from apps to 2D games, so I don’t want to make two jumps at once. The demos are pretty convincing as to the capabilities of the engine, and writing code in Objective-C makes me feel confident enough that I will be able to understand everything that’s going on in my project. To me, Cocos2D feels like a comfortable middle ground between the low-level Core & OpenGL libraries, and the high-level Torque and Unity frameworks. Although the documentation is not as good as I would like it to be, there are active forums and Cocos2D is growing rapidly in popularity. It’s with this blog that I’m hoping to help fill the documentation hole, and provide a useful set of tutorials for people who are in the position I’m in now.

If you still haven’t made up your mind, there are some other options. Oolong, GameSalad, and Shiva are all iPhone game frameworks, but I felt they weren’t mature enough to consider seriously. Who knows though, by the time you read this entry they might be! If you’re not a big fan of Objective-C and are looking for something higher level, this thread gives some useful insights into the merits of both Unity and Torque. Finally, if you’re still feeling like you want to go with OpenGL or the Core libraries, I’d strongly recommend you keep an eye on this blog – I’m positive Cocos2D has a lot to offer you.

Leave a Comment more...

Why Develop iPhone Games?

by Ben on Jan.30, 2010, under General Games Development

I have been developing iPhone applications on and off for around half a year now, and it is one of the most enjoyable development experiences I’ve had. The supplied controls look great, and the marketplace is huge and easily accessible. There’s been a few successes for me along the way, in particular PhotoCaddy, a guide for DSLR photographers which was featured by Apple in the “whats hot” section and made it to #8 on the charts.

For the last few months I’ve been considering jumping into the games arena. In my mind, this is a fairly big move, as it means departing from the standard Apple controls, and entering a very competitive arena. I’ve already made my decision, but you might not have made yours, so let’s look at a few reasons for and against developing iPhone games.

Reasons For Developing iPhone Games

  • The market is huge. While it’s difficult to get reliable figures on how many people actually own iPhones, there have been over 2 billion apps downloaded from the App Store. That’s a very big number!
  • Games are fun. I like playing games, especially small fun time wasters, which just happens to be the sort of game the iPhone is well suited to. Will developing games be as fun as playing them? More so, I think.
  • The challenge. I don’t expect writing a game to be easy, in fact I expect it to be considerably more difficult than anything I’ve written for the iPhone thus far. But, overcoming a challenge leads to great satisfaction.
  • Chance of success. Everybody loves games, and the idea that people will be playing my game on the bus, telling their friends about it, and writing blog entries on how to get the best scores, really excites me.
  • The Apple iPad is coming. Whether or not you like the product, it is going to sell, and people are going to play games on it. Personally, I believe it will be a great platform for some games, and those that take advantage of it’s capabilities could do very well.

Reasons to Avoid iPhone Games Development

  • The market is saturated. There’s 140,000 apps in the App Store at last count, and a large proportion of these are games. There’s a lot of competition, and it will be hard to get noticed.
  • Complexity. Making a game is a lot more difficult than dropping a few UITableViews onscreen. There’s frame rates to worry about, mathematics and physics, and complex object interactions.
  • Higher expectation of quality. There’s some really great apps in the App Store at the moment, but often the highest quality ones aren’t the highest selling – it’s usually the ones that have marketed themselves well, and do some job in a reasonable manner. This strategy is unlikely to hold up with games.

So why develop games? For me, the strongest motivator is that it’s always something I’ve had an interest in, and now seems like a great time to get started. iPhone sales are booming, the iPad is coming, and I’m fortunate enough to have some free time on my hands.

If you’re new to iPhone games development, or you’re still trying to make up your mind, this blog will be your friend along the way. This is a completely new area for me, and I want to provide a resource for those who are getting started. I plan on posting samples of code, links to anything I find useful, as well as discussions and screens on development progress as I build my first game. I’d love for you to join me.

1 Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...

Archives

All entries, chronologically...