Twitter RSS
magnify
Home Chipmunk Physics Engine Getting Started with Cocos2d and Chipmunk Physics – Part 1
formats

Getting Started with Cocos2d and Chipmunk Physics – Part 1

Getting started with Cocos2d can seem a bit intimidating since there are so many things to learn.

This two part tutorial should help you tackle the Cocos2d learning curve and get you rolling towards creating an iPhone app you can publish in the Apple App store.

Overview of this two-part tutorial: Getting Started with Cocos2d and Chipmunk

Part 1: In part 1 (this post) you will learn how to get Cocos2d, install the Cocos2d Xcode templates, and create your first Cocos2d + Chipmunk app. We then walk though some of the basics of Cocos2d and Chipmunk.

Part 2: In Part 2, you learn about how the basic building blocks work in Cocos2d such as sprites, buttons, and labels and how the basic Chipmunk building blocks such as bodies and shapes can be used. The complete code of the HelloWorld interface and implementation files of the app created in Part 1 are discussed in great detail.

What is Cocos2d?

Cocos2d 2.0 is an open source video game engine capable of creating a large variety of genres of two dimensional video games. It is built on top of OpenGL ES 2.0 and is packed full of features.

One great thing about Cocos2d is that it is designed as a layer of abstraction between the developer and OpenGL ES and it is possible to create a great game without knowing anything about OpenGL.

Cocos2d is free to download and use for personal or commercial purposes. It requires that you have Xcode and are familiar with the Xcode integrated development environment and Objective C 2.0. You don’t have to be a master at these to get up and running with Cocos2d, but a basic understanding is required. If you do not already have XCode or need a primer tutorial on using Xcode, check out this article about downloading and getting to know Apple’s XCode integrated development environment.

It is important to note that at the time of this writing Cocos2d has branched into two versions: Cocos2d 1.0.1 and Cocos2d 2.0 rc2. The major differences between Cocos2d 1.0.1 and Cocos2d 2.0 rc2 is that the 1.0.1 version is based on OpenGL ES 1.1 and the Cocos2d 2.0 rc2 is based on OpenGL ES 2.0. The 2.0 version requires a minimum target iOS of 4.0. While version 2.0 is officially considered an unstable build, it will very soon be released as a stable version if no serious issues are identified with it. Heyalda has published the game All Star Rally using Cocos2d 2.0 rc2 as a foundation and the game is quite stable.

Not related to this article, but worth mentioning, is that Cocos2d is built on top of OpenGL ES and it is possible to add 3d features to your game. This can be done via custom OpenGL ES code or by leveraging the Cocos3d add-on for Cocos2d that was created by The Brenwill Workshop.

Downloading and setting up Cocos2d 2.0

For this series of articles on building a game with Cocos2d, the Cocos2d 2.0 rc2 version will be used.

The following steps can be followed to download Cocos2d 2.0 rc2 and install the Cocos2d Xcode 4 templates that enable Xcode to automatically create the baseline code for three different types of Cocos2d apps.

1) Create a folder in a convenient location on your mac titled Cocos2d. When future updates of Cocos2d are released, you can repeat these steps to get the latest version.

2) Download Cocos2d here. Be sure to get the Cocos2d 2.x version if you want to follow along in this tutorial.

3) Move the cocos2d-iphone-2.0-rc2.tar.gz file to the Cocos2d folder created in step 1 and double-click the cocos2d-iphone-2.0-rc2.tar.gz file to un-tar and decompress it.

4) Open a terminal window located in the Dock under Applications->Utilities->Terminal.app

5) Drag the install-templates.sh file from the cocos2d-iphone-2.0-rc2 folder into the terminal and press return/enter key. This will install the Cocos2d Xcode templates.

The Cocos2d Xcode 4 templates are used by Xcode 4 when creating a new Cocos2d app. Three different templates exist at the time of this writing that automatically create the baseline code to get you started.

The first template is to create a Cocos2d app that does not use a physics engine. The second is used to create a Cocos2d app that uses the Box2d physics engine, and the third is used to create a Cocos2d app that uses the Chipmunk physics engine.

While these templates are very helpful, they are not magic. What they do is copy the required class files for the type of app that you are creating and then add the basic code to get the app up and running. So technically you could start with the first Cocos2d template that does not use a physics engine and then manually copy the physics engine class files into your project and add the necessary initialization code. But if you are starting from scratch, the templates are very helpful.

Creating Your First Cocos2d App

This next part of this tutorial may feel a bit like cheating since it is so easy to get a Cocos2d app up and running.

Follow these steps to create a new Cocos2d game that uses the Chipmunk physics engine and then run it in the iPhone Simulator.

1) If Xcode is already open, it is necessary to quit the application and start it again to enable the newly installed Cocos2d templates.

2) Click the Xcode icon in the Dock to launch the XCode application.

3) In the Welcome to Xcode dialog, click on Create a New Xcode Project. If for some reason the dialog does not appear and Xcode is open, you can create a new project by selecting the menu File -> Create a New Xcode Project in the upper left corner of the screen.

4) In the Choose a template for your new project dialog that appears, under iOS on the left choose cocos2d and then select the cocos2d_chipmunk template and then click next.

5) Assign a product name to the app. Do not add any spaces to the name or the template will not work properly. I recommend using camel caps to name the app something like TruckRacingGame. This name will not be visible to the end user if you were to publish this app.

6) For the company identifier, use your reverse domain name format company identifer. Click next.

Q: What is a company product name, company identifier, and bundle identifier? A: The combination of the Product Name and Company Identifier is called the Bundle Identifier and should be unique for each app. For this app I chose TruckRacingGame for the product name and my company identifier is com.heyalda. Xcode then puts these together to make the Bundle Identifer, which is com.heyalda.TruckRacingGame. The bundle identifier is used to determine where to copy an app that is being added to a device or in the simulator. So if the name is the same as another app, then it will overwrite the existing app on install. Also, if you publish an app to the Apple App store, having this configured properly for your company is a must.

7) The next dialog should prompt you to select a folder to save the newly created project.

Q: Where should I save my project? A: I recommend that you create a new folder to store this project. This will also be where you can store all of the resource for this project. Create a folder with an appropriate name and location.

Q: What is Git? A: Git is a software source code management (source control) application created by Linus Torvalds that is included in Xcode. Git works great for version control and it is integrated into Xcode. I recommend clicking on the Create a local git repository for this project check box so that you can try it out.

8) After selecting the folder to store your new Cocos2d project and choosing weather or not to enable git, click on the create button and you should now have your first Cocos2d app to play with.

9) Verify that iPhone 5.1 (or newer) simulator is the selected target device as shown in the above image.

10) Click the Run button in the upper left corner of Xcode. This will build and run your newly created Cocos2d app in the iPhone simulator. You should see the iOS simulator running the newly created Cocos2d-Chipmunk app shown in the following image. Tap the screen to add a new characters to the game world where each character is modeled by Chipmunk physics bodies, shapes and Cocos2d sprites. Pat yourself on the back for a job well done on creating your first Cocos2d app.

A Note about Game Architecture

This tutorial covers getting a sample HelloWorld app up and running in Xcode.

When an actual production game is created, a proper game architecture should be created by formulating requirements, carefully considering the use cases, flow and overall experience of the game and then take time to design and implement the game in a manner where the code, resources, scripting, and other components are easy to understand and support. This is a very important topic and will be covered in detail in a future blog post coming soon.

Getting to Know Cocoos2d and Chipmunk Physics Engine

Granted that this app is far from being a polished game, it is a good start in the direction of getting an understanding of how Cocos2d works.

However, keep in mind that there are often multiple ways to accomplish a task in Cocos2d. Some of the ways that things are done in this sample app are not very practical or desirable ways of doing things in an actual production game. For example, a sprite sheet is loaded and the parsing of the sprite sheet is hard coded into the app. There are better ways to deal with loading a sprite sheet that will be briefly discussed in this article.

First I will discuss the important fundamental concepts you should understand.

Important Cocos2d Concepts

The foundation of Cocos2d from a game developers perspective are the CCDirector, CCNode, CCScene, CCLayer, and CCSprite classes.

The cocos2d CCDirector class is subclass of Apple’s Foundation Framework NSObject class (In the Cocos2d 2.0 release, the director is now a subclass of UIViewController). A singleton instance of the CCDirector effectively orchestrates each Cocos2d game. The singleton instance is the first Cocos2d object that is created when the game launches.

The CCDirector instance must be configured with some basic settings as will be seen in the code below. It is used to launch the first game scene, control scene transitions, and can provide low level details about how the game is running.

The cocos2d CCNode is a base class for several game objects in Cocos2d. The CCNode is a construct that contains read-write properties such as position, scale, skewX, skewY, rotation, contentSize, anchorPoint, visible and several others. The CCNode also contains many other details such as an array of child nodes, a pointer to a parent node if one exists, a pointer to custom user data, and various other functionality. To learn more about the functionality of the CCNode, in the project navigator expand the libs group and then the cocos2d group and click on the CCNode.h header file.

The cocos2d CCScene is a child class of the CCNode class. It only contains about 5 lines of code. The only customization code in the CCScene class is shown here.


CGSize s = [[CCDirector sharedDirector] winSize];
self.isRelativeAnchorPoint = NO;
anchorPoint_ = ccp(0.5f, 0.5f);
[self setContentSize:s];

The Scene is basically a CCNode but the size of the CCScene is set to match the main UIWindow of the app and the anchorPoint is set to the center of the main UIWindow.

The cocos2d CCLayer class is a subclass of the CCNode class. CCLayer adds UITouch and Accelerometer functionality.

The cocos2d CCSprite class is a subclass of CCNode and adds a lot of functionality to the CCNode, primarily related to adding textures and manipulating textures.

The cocos2d CCSpriteBatchNode class is a subclass of CCNode and is used to gain efficiencies in loading image files, storing images textures in RAM, and drawing sprites. This will be discussed further in part 2 of this tutorial series.

All Cocos2d games start by creating a CCScene and a CCLayer, then the CCLayer is added to the CCScene, and then the CCDirector runs the initial CCScene object.

CCLayer is by default a delegate class for the touch and accelerometer events that Cocos2d manages for you. When you create sprites or sprite batch nodes you need to add them to a CCLayer (or CCNode) so that they will be drawn.


-(void) update:(ccTime) delta{

    // Do the main game update logic here

}

The objects discussed so far a just a very small sample of what can be done with Cocos2d. But lets move on to the Chipmunk Physics engine for now.

Important Chipmunk Physics Concepts

Chipmunk was created and is supported by Scott Lembcke and is written in C. There is an Objective C wrapper for Chipmunk that can downloaded from the creators of Chipmunk Physics. Since the C api is included with Cocos2d, this tutorial will discuss using the C api.

There is very detailed documentation about Chipmunk Physics engine that can be found here.

Each class that uses Chipmunk must import the chipmunk.h header file with the following code near the top of either the interface file or implementation file.


#import "chipmunk.h"

Since Chipmunk is written in C, the objects (structs are not objective C objects, but they are objects) that are created are actually C structures known as structs. Don’t let this intimidate you. They are easy to work with a quite efficient.

The cpSpace struct is created and configured to manage the physics simulation that will run in the game.

The cpBody structs are created to simulate bodies with a two dimensional size and mass in the form of a line segment, circle, or convex polygon. They are created and added to the single spSpace that is created for a game. Bodies do not interact with collision detection in the physics simulation. The geometric shape of a body is only relevant when calculating the moment of inertia that is assigned to the body. When the body object is created, it is assigned a mass and a moment of inertia.

The cpShape struct defines a segment, circle, box, or polygon shape that can be added to a body. Multiple shapes can be added to each body. Shapes interact with collision detection in the physics simulation. The shapes you choose to use can impact performance of the simulation. The segment shape is the most efficient collision detection shape, followed by the circle, the box, and then the more complex polygon.

The cpConstraint struct defines a relationship between cpBody objects. Multiple constraints can be assigned to a pair of bodies to create interesting interactions. Note that constraints are not used in the Chipmunk app we create above in this tutorial.

Example: For an example of how these four structs could be used, consider creating a truck with a front and rear wheel. One body would represent each wheel and one body wold represent the rectangle of the truck. A cpSpace object would be crated and configured. The front wheel body, rear wheel body, and truck body would be added to the cpSpace object. Shapes for the wheels and the truck body would be created and added to the three body structs. A cpGrooveJoint and cpDampedSpring constraint would be combined to constrain the front wheel movement relative to the truck body. Another cpGrooveJoint and cpDampedSpring would be combined and applied between the rear wheel and truck body. If setup properly the physics would simulate quite nicely a truck with bouncy suspension connected to its wheels. A cpSimpleMotor joint could also be defined between each wheel and the truck body. The result would be a simulation of a four wheel drive truck.

Overview of Code Created by the Cocos2d Chipmunk Template

Now that you have a working Cocos2d app and some background about the fundamentals of Cocos2d and Chipmunk, you can begin to explore the code created by the template to get a better understanding of how Cocos2d and Chipmunk physics can be used to create a game.

Lets start by taking a look at what code was added to the project for you by the Cocos2d Chipmunk template.

In the project navigator, expand the group (looks like a yellow folder but is a group and not a folder reference) that is labeled with the product name that you selected when creating the app. You should see the AppDelegate, RootViewController, and HelloWorldLayer header files (.h) and implementation files (.m).

The AppDelegate is a standard class that all iOS apps have. It must conform the the UIApplicationDelegate protocol. These are all the ‘applicationDid’ and ‘applicationWill’ selectors you see in the AppDelege.m file. An instance of this class is created by the main.m file that can found in the Supporting Files group. The instance of AppDelegate is the first customized object that is created when the app launches. Click on the AppDelegate.m file to take a look at the - (void) applicationDidFinishLaunching:(UIApplication*)application selector. This is the first selector that is called when after the single instance of AppDelegate is created. This selector and its code are shown here.

- (void) applicationDidFinishLaunching:(UIApplication*)application
{
    // Init the window
    window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];

    CCDirector *director = [CCDirector sharedDirector];

    // Init the View Controller
    viewController_ = [[RootViewController alloc] initWithNibName:nil bundle:nil];
    viewController_.wantsFullScreenLayout = YES;

    //
    // Create the EAGLView manually
    //  1. Create a RGB565 format. Alternative: RGBA8
    //    2. depth format of 0 bit. Use 16 or 24 bit for 3d effects, like CCPageTurnTransition
    //
    //
    EAGLView *glView = [EAGLView viewWithFrame:[window_ bounds]
         pixelFormat:kEAGLColorFormatRGB565    // kEAGLColorFormatRGBA8
         depthFormat:0                        // GL_DEPTH_COMPONENT16_OES
    ];

    // attach the openglView to the director
    [director setOpenGLView:glView];

    // Enables High Res mode (Retina Display) on iPhone 4 and maintains low res on all other devices
    //    if( ! [director enableRetinaDisplay:YES] )
    //        CCLOG(@"Retina Display Not supported");

    [director setAnimationInterval:1.0/60];
    [director setDisplayStats:kCCDirectorStatsFPS];

    // enable multi touches
    [glView setMultipleTouchEnabled:YES];

    // make the OpenGLView a child of the view controller
    [viewController_ setView:glView];

    // make the View Controller a child of the main window
    [window_ addSubview: viewController_.view];

    [window_ makeKeyAndVisible];

    // Default texture format for PNG/BMP/TIFF/JPEG/GIF images
    // It can be RGBA8888, RGBA4444, RGB5_A1, RGB565
    // You can change anytime.
    [CCTexture2D setDefaultAlphaPixelFormat:kCCTexture2DPixelFormat_RGBA4444];

    // PVR Textures have alpha premultiplied
    [CCTexture2D PVRImagesHavePremultipliedAlpha:YES];

    // Removes the startup flicker
    [self removeStartupFlicker];

    // create scene
    CCScene *scene = [CCScene node];
    [scene addChild:[HelloWorldLayer node]];

    // Run the intro Scene
    [[CCDirector sharedDirector] runWithScene:scene];
}

The code here might seem a bit cryptic, but it is a good idea to have at least a basic understanding of what it does.

The line numbers referred to here are the line numbers of the above block of code, not the line numbers from the AppDelegeate.m source file.

Line 6 creates the singleton instance of the Cocos2d CCDirector.

Lines 4, 9, and 10 create the UIWindow and the UIViewController that all iPhone and iPad apps are required to have. The RootViewController is a custom subclass of UIViewController that was copied into this project by the Cocos2d template.

Lines 18-21 create the main OpenGL view that is added to the instance of the RootViewController on line 37 and the view of the RootViewController is in turn added to the main UIWindow on line 40. No need to think much about these for now. Just know that they exist.

You will likely want to revisit pixelFormat setting of the EAGLView to try out different settings for the tradeoff between image quality and performance. The depthFormat settings can be useful if you choose to implement 3d objects into your game.

Regarding pixel format, if the pixelFormat of the EAGLView is changed, you will likely want to also change the CCTexture2D’s defaultAlphaPixelFormat (line 47) to the equivalent setting.

Line 56 and 57 create an instance of the HellowWorldLayer, add it to a CCScene object, and then line 60 tells the director to run that scene.

This post covered a lot of information. If the topics discussed are new to you, take some time to dig around the code in the AppDelegate and HellowWorldLayer classes to get a sense of the structure of the sample app.

In the next post titled Getting Started with Cocos2d and Chipmunk – Part 2 the complete code of the HellowWorld.h and HellowWorld.m files will be discussed in detail.

 
 Share on Facebook Share on Twitter Share on Reddit Share on LinkedIn
Comments Off  comments