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

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 »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
Medical Assistant - Orthopedics *Apple* Hil...
Medical Assistant - Orthopedics Apple Hill York Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Now Read more
*Apple* Systems Administrator - JAMF - Activ...
…**Public Trust/Other Required:** None **Job Family:** Systems Administration **Skills:** Apple Platforms,Computer Servers,Jamf Pro **Experience:** 3 + years of Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.