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

The Legend of Heroes: Trails of Cold Ste...
I adore game series that have connecting lore and stories, which of course means the Legend of Heroes is very dear to me, Trails lore has been building for two decades. Excitedly, the next stage is upon us as Userjoy has announced the upcoming... | Read more »
Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »

Price Scanner via MacPrices.net

Sunday Sale: Apple Studio Display with Standa...
Amazon has the standard-glass Apple Studio Display on sale for $300 off MSRP for a limited time. Shipping is free: – Studio Display (Standard glass): $1299.97 $300 off MSRP For the latest prices and... Read more
Apple is offering significant discounts on 16...
Apple has a full line of 16″ M3 Pro and M3 Max MacBook Pros available, Certified Refurbished, starting at $2119 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free... Read more
Apple HomePods on sale for $30-$50 off MSRP t...
Best Buy is offering a $30-$50 discount on Apple HomePods this weekend on their online store. The HomePod mini is on sale for $69.99, $30 off MSRP, while Best Buy has the full-size HomePod on sale... Read more
Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more

Jobs Board

Licensed Practical Nurse - Womens Imaging *A...
Licensed Practical Nurse - Womens Imaging Apple Hill - PRN Location: York Hospital, York, PA Schedule: PRN/Per Diem Sign-On Bonus Eligible Remote/Hybrid Regular Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Operating Room Assistant - *Apple* Hill Sur...
Operating Room Assistant - Apple Hill Surgical Center - Day Location: WellSpan Health, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.