TweetFollow Us on Twitter

iPhone, iPad, & iPod Touch Game Development Frameworks

Volume Number: 26
Issue Number: 02
Column Tag: iPod SDK, Games

iPhone, iPad, & iPod Touch Game Development Frameworks

Tools for building 2D games

by Rich Warren

Introduction

Games remain one of the most popular categories for applications on the iPhone, with over 20,000 active titles in the iTunes App store. More importantly, gaming titles regularly dominate the App Store's Top Charts for free, paid and top grossing apps. Not surprisingly, many developers are interested in getting in on this action. Unfortunately, developing a quality game is not easy. It takes a wide range of skills to create the compelling music, visually stunning artwork and fun game play necessary for success. Even the programming tasks present unique challenges, as developers struggle to squeeze every last drop of performance out of their target machines.

In this article, we will look at tools to help simplify the process. Now, we're not going to tackle music, sound effects, artwork, or game design. You're on your own there. We will, however, look at two libraries that can greatly ease the development challenge, helping you create high-performance 2D games. This article will introduce the Cocos2D for iPhone graphics framework and the Chipmunk physics engine. Cocos2D will manage the organization of our scenes, the display of all our entities, and handle the basic timing of events. Chipmunk will manage the movement, collisions and other interactions between entities in the scene. We will start with a high-level overview. Then, next month, we will build a simple game application from the ground up.

Cocos2D for iPhone Framework

Let's start with an important question. Why do we even need a graphics framework? Cocoa already provides a wide range of libraries and frameworks for handling graphics on the iPhone. UIKit offers a simple-to-use API for basic 2D drawing. Quartz 2D adds more-powerful 2D drawing tools for lines, shapes, patterns, gradients and images, while Core Animation supplies additional support for smooth motion and dynamic feedback. Alternatively, OpenGL ES provides high-performance 2D and 3D graphics processing, unlocking the full power of the iPhone's GPU.

As you can see, graphic programming is basically divided between the easy-to-use tools in the Cocoa frameworks (UIKit, Quartz 2D and Core Animation) and the full-bore power of OpenGL ES. Many games, particularly puzzle or turn-based games, may not need high performance. In those cases, the Cocoa frameworks provide an excellent solution. However, if you want higher performance, you need to use OpenGL.

Unfortunately, OpenGL is a large, complex and (frankly) intimidating library. Ultimately, there is no substitution; if you want to squeeze every last drop of performance out of your application, you need to cowboy up and master OpenGL ES. However, to throw down some Voltaire, the perfect is the enemy of the good. Finishing your project is more important than hitting some optimal performance benchmark. For most games, there is a sweet spot between performances and ease-of-use. All we need is a framework that wraps up OpenGL and gives us access to the raw power of the GPU, while still providing an Objective-C interface and developer-friendly API. Sure, such a framework might impose a slight performance cost, but it will still be a big step up from Quartz 2D and friends. Enter Cocos2D for iPhone.

Cocos2D for iPhone is an Objective-C port of the original python-based Cocos2D graphics engine. This library presents an easy-to-use framework for building 2D games and other graphic-oriented, interactive applications on the iPhone. It provides support for 2D scenes, sprites, actions, effects, transitions and more. Two sub-libraries provide additional support: Cocos Live provides access to the online High Score Server, while CocosDenshion provides an easy-to-use sound engine. Cocos2D for iPhone also comes bundled with several compatible 3rd party libraries: two different 2D physics engines (Chipmunk and Box2D), a JSON parser (TouchJSON) and an OGG audio decoder (Tremor).

Chipmunk Physics Engine

The arguments for using a physics engine are more straightforward. We want our objects to slide, roll, fall, bounce, stack and collapse in a realistic manner. While we could program all the interactions by hand, this would quickly become extremely tedious and error-prone. Especially since we need to get the physics right while performing the necessary calculations in a highly efficient manner. Using a well-tested third-party library just makes sense.

As mentioned earlier, Cocos2D for iPhone includes two compatible physics engines. Both perform similar functions. In fact, Chipmunk is largely based on an earlier, pre-release version of Box2D. They both let us define the physical characteristics of our objects. We can apply forces to those objects, and the physics engine will calculate their motion over time, automatically handling any collisions and interactions between objects.

Both libraries perform well. They provide largely the same features, though there are some exceptions around the edges. The major difference is one of style; Box2D was written in C++, while Chipmunk is written in C. I chose to focus on Chipmunk, mostly because mixing C++ and Objective-C adds a little more complexity to the project. But, you should definitely check out both libraries. Box2D's Continuous Collision Detection may prove particularly useful for catching collisions between very fast objects and very thin targets.

Note: as of this writing, the stable release of Cocos2D for iPhone (version 0.8.2) does not contain the most recent version of Chipmunk (version 5.1.0). The more recent releases include a number of new features (including new joints and segment raycasting). We won't use these during the tutorial next month, but you may want to upgrade Chipmunk before starting your own projects.

Getting Cocos2D for iPhone

Download Cocos2D for iPhone from their web site, http://www.cocos2d-iphone.org. As I'm writing this, the current stable release is version 0.8.2. However, I would recommend trying to use the most recent stable release available when building your own projects. In particular, the 0.99 release candidate includes Chipmunk version 5.1 and iPad support. Save the extracted folder somewhere. Then you'll need to install the Xcode templates. Open up Terminal and navigate to the cocos2d-iphone root directory. Then run the following command:

./install_template.sh

This will install three new project templates: a basic cocos2d application, a cocos2d Chipmunk application and a cocos2d Box2d application. It's important to notice, these templates are actually mini programs in their own right. You can compile and run them, and they give you a very simple game without writing any code at all.


Cocos2D's templates

You can learn a lot about the organization of Cocos2D applications by examining the template code. I'll leave that as an exercise for the reader. In particular, you may want to check out the HelloWorldScene class in the Cocos2D Chipmunk template. In part 2, we will look at a somewhat different approach, and it is well worth understanding both.

Also, Cocos2D for iPhone comes with a large number of examples demonstrating a vast range of features. I highly recommend exploring these, especially the ChipmunkTest and Box2DTestBed. To run the examples, double click on the cocos2d-iphone.xcodeproj project file in the cocos2d-iphone root directory.

This project sets the default SDK to version 2.2.1, which is no longer available in current releases of Xcode. You can change the default in the build settings, but the easiest fix is to simply change the SDK to a valid option in the Overview pull-down menu (leftmost button on the toolbar). I chose the 3.1.2 simulator. Next, select one of the executable targets in the Active Target pull-down menu (executables start at AccelViewportTest). Xcode will automatically set the corresponding Active Executable. Build and run. If you see a feature you like, crack open the code and look at how it is done.


Setting the SDK


ChipmunkTest In Action

Note: not all of the examples compile correctly, so don't get discouraged if you run into problems. Most, however, run fine.

Code Overview

Finally, let's take a quick look at some of the classes/structures we will be using to build our game. We'll start with Cocos2D. We will really only concern ourselves with 4 objects: Scene, Layer, Sprite and Director. The Scene encapsulates a largely independent portion of the game. Scenes can represent a wide range of elements: opening videos, menus, various levels and stages within a game and even the credits at the end. Each Scene has one or more Layers that hold the content of the scene, and each Layer can contain any number of Sprites. Sprites encapsulate graphic elements and animations, usually loaded from one or more image files.

Scene, Layer and Sprite all subclass the CocosNode class, which provides a wide range of transformations, including moving, rotating and scaling. You can, for example, move an entire Layer, and any Sprites stored in that Layer will automatically move along with it.

The Director is a singleton object that manages both the game's run loop and the transitions between Scenes. It maintains a stack of Scenes and manages the current Scene. New Scenes can be pushed onto the stack. This pauses the current Scene, and starts the new Scene. When the Scene is then popped off the stack, the paused Scene automatically starts up again.

The application we develop next month will use a single Layer within a single Scene, and the Layer will do most of the work. More complex architectures are, of course, possible.

Next, let's look at Chipmunk. Being a C library, Chipmunk does not provide any objects. Instead, we have a number of structures, and the functions to manipulate them. In particular, we will be working with cpSpace, cpBody, cpShape and cpVect structures.

cpSpace defines our world. It maintains a list of the bodies, shapes, joints and other physical elements. It also stores the global configuration data, like the number of iterations used by the impulse solver, or the global gravity vector.

cpBody stores the physical characteristics for an entity in our space. This includes the entity's mass, moment of inertia, position, velocity, rotation angle, angular momentum, force and torque. Chipmunk will use these elements to calculate the entity's new position and angle each time step.

While cpBody defines how an entity behaves by itself, cpShape defines how entities interact. Each body may have one or more shapes. Shapes can be single lines, circles or convex polygons. A single body can have more than one shape associated with it, allowing us to build complex shapes. cpShapes can also be static or active. Static shapes represent immobile entities in our scene. Active shapes can move. Chipmunk will optimize its update code appropriately.

Finally, the cpShape contains a number of surface properties: the elasticity, friction and surface velocity. Elasticity and friction can be rated from 0.0 to 1.0. Elasticity measures how bouncy an object is. A shape with 0.0 elasticity won't bounce at all, while 1.0 will rebound without loosing any velocity. Similarly, friction measures how easily the object slides. Imagine a ramp. If it has a 0.0 friction, objects will slide down the ramp without slowing. With a 1.0 friction, objects won't slide at all (though, round objects might roll). We won't use surface velocity in part 2; however, it could be used to model things like conveyor belts and escalators.

Note: the Chipmunk documentation states that, due to a bug, you should not use Elasticity values of 1.0. And, really, the point of using a physics engine is to make things look realistic. No real objects are perfectly elastic. Keep the elasticity less than 1.0 and everyone remains happy.

Our last structure, cpVect, is simply an alias for CGPoint. However, it implies that the x- and y-values should be interpreted as vectors (for example, velocity, impulse or force vectors). Since this is simply an alias, you can pass cpVects to an object that requires a CGPoint, and vice-versa. For consistency's sake, I try to use cpVect when working with Chipmunk code and CGPoint when working with Cocos2D, though I undoubtedly mixed them up on occasion.

In general, you use Chipmunk to control how objects move and interact, and Cocos2D to display the objects. We schedule a Selector with our Layers, and that Selector is called each frame to update the Layer. During the update step, we call cpSpaceStep. This will update the position and velocity of all our bodies, and call any callback methods triggered by collisions. Then we update the position of each Sprite based on its corresponding cpBody.

In almost all cases, an active entity will be defined by a Sprite, a cpBody and one or more cpShapes. Most of the time, we control the entity by applying impulses or forces to its cpBody. We use two different libraries to define a single entity, so it's easy to get confused. Just remember, if you're concerned with how an entity appears, we're probably dealing with Cocos2D. If we're concerned with how the entity moves or interacts with its environment, that should be Chipmunk.

Also Note: both the cpBody and the Sprite maintain the entities position and rotation. There may be a few exceptions, but you almost always want to set the Sprite's values equal to the cpBody's. In general, you should not change the cpBody values directly. Apply impulses and forces, and let the physics engine do its job.

And that's pretty much it. Next time we'll jump into the code with both feet and build our own game. Until then, take some time to poke around the library, play with the examples, and get a feel for how all the parts fit together.


Rich Warren lives in Honolulu, Hawaii with his wife, Mika, daughter, Haruko, and his son, Kai. He is a software engineer, freelance writer and part time graduate student. When not playing on the beach, he is probably writing, coding or doing research on his MacBook Pro. You can reach Rich at rikiwarren@mac.com, check out his blog at http://freelancemadscience.blogspot.com/ or follow him at http://twitter.com/rikiwarren.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.