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

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance 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
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.