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

Whitethorn Games combines two completely...
If you have ever gone fishing then you know that it is a lesson in patience, sitting around waiting for a bite that may never come. Well, that's because you have been doing it wrong, since as Whitehorn Games now demonstrates in new release Skate... | Read more »
Call of Duty Warzone is a Waiting Simula...
It's always fun when a splashy multiplayer game comes to mobile because they are few and far between, so I was excited to see the notification about Call of Duty: Warzone Mobile (finally) launching last week and wanted to try it out. As someone who... | Read more »
Albion Online introduces some massive ne...
Sandbox Interactive has announced an upcoming update to its flagship MMORPG Albion Online, containing massive updates to its existing guild Vs guild systems. Someone clearly rewatched the Helms Deep battle in Lord of the Rings and spent the next... | Read more »
Chucklefish announces launch date of the...
Chucklefish, the indie London-based team we probably all know from developing Terraria or their stint publishing Stardew Valley, has revealed the mobile release date for roguelike deck-builder Wildfrost. Developed by Gaziter and Deadpan Games, the... | Read more »
Netmarble opens pre-registration for act...
It has been close to three years since Netmarble announced they would be adapting the smash series Solo Leveling into a video game, and at last, they have announced the opening of pre-orders for Solo Leveling: Arise. [Read more] | Read more »
PUBG Mobile celebrates sixth anniversary...
For the past six years, PUBG Mobile has been one of the most popular shooters you can play in the palm of your hand, and Krafton is celebrating this milestone and many years of ups by teaming up with hit music man JVKE to create a special song for... | Read more »
ASTRA: Knights of Veda refuse to pump th...
In perhaps the most recent example of being incredibly eager, ASTRA: Knights of Veda has dropped its second collaboration with South Korean boyband Seventeen, named so as it consists of exactly thirteen members and a video collaboration with Lee... | Read more »
Collect all your cats and caterpillars a...
If you are growing tired of trying to build a town with your phone by using it as a tiny, ineffectual shover then fear no longer, as Independent Arts Software has announced the upcoming release of Construction Simulator 4, from the critically... | Read more »
Backbone complete its lineup of 2nd Gene...
With all the ports of big AAA games that have been coming to mobile, it is becoming more convenient than ever to own a good controller, and to help with this Backbone has announced the completion of their 2nd generation product lineup with their... | Read more »
Zenless Zone Zero opens entries for its...
miHoYo, aka HoYoverse, has become such a big name in mobile gaming that it's hard to believe that arguably their flagship title, Genshin Impact, is only three and a half years old. Now, they continue the road to the next title in their world, with... | Read more »

Price Scanner via MacPrices.net

B&H has Apple’s 13-inch M2 MacBook Airs o...
B&H Photo has 13″ MacBook Airs with M2 CPUs and 256GB of storage in stock and on sale for up to $150 off Apple’s new MSRP, starting at only $849. Free 1-2 day delivery is available to most US... Read more
M2 Mac minis on sale for $100-$200 off MSRP,...
B&H Photo has Apple’s M2-powered Mac minis back in stock and on sale today for $100-$200 off MSRP. Free 1-2 day shipping is available for most US addresses: – Mac mini M2/256GB SSD: $499, save $... Read more
Mac Studios with M2 Max and M2 Ultra CPUs on...
B&H Photo has standard-configuration Mac Studios with Apple’s M2 Max & Ultra CPUs in stock today and on Easter sale for $200 off MSRP. Their prices are the lowest available for these models... Read more
Deal Alert! B&H Photo has Apple’s 14-inch...
B&H Photo has new Gray and Black 14″ M3, M3 Pro, and M3 Max MacBook Pros on sale for $200-$300 off MSRP, starting at only $1399. B&H offers free 1-2 day delivery to most US addresses: – 14″ 8... Read more
Department Of Justice Sets Sights On Apple In...
NEWS – The ball has finally dropped on the big Apple. The ball (metaphorically speaking) — an antitrust lawsuit filed in the U.S. on March 21 by the Department of Justice (DOJ) — came down following... Read more
New 13-inch M3 MacBook Air on sale for $999,...
Amazon has Apple’s new 13″ M3 MacBook Air on sale for $100 off MSRP for the first time, now just $999 shipped. Shipping is free: – 13″ MacBook Air (8GB RAM/256GB SSD/Space Gray): $999 $100 off MSRP... Read more
Amazon has Apple’s 9th-generation WiFi iPads...
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
Discounted 14-inch M3 MacBook Pros with 16GB...
Apple retailer Expercom has 14″ MacBook Pros with M3 CPUs and 16GB of standard memory discounted by up to $120 off Apple’s MSRP: – 14″ M3 MacBook Pro (16GB RAM/256GB SSD): $1691.06 $108 off MSRP – 14... Read more
Clearance 15-inch M2 MacBook Airs on sale for...
B&H Photo has Apple’s 15″ MacBook Airs with M2 CPUs (8GB RAM/256GB SSD) in stock today and on clearance sale for $999 in all four colors. Free 1-2 delivery is available to most US addresses.... Read more
Clearance 13-inch M1 MacBook Airs drop to onl...
B&H has Apple’s base 13″ M1 MacBook Air (Space Gray, Silver, & Gold) in stock and on clearance sale today for $300 off MSRP, only $699. Free 1-2 day shipping is available to most addresses in... Read more

Jobs Board

Medical Assistant - Surgical Oncology- *Apple...
Medical Assistant - Surgical Oncology- Apple Hill Location: WellSpan Medical Group, York, PA Schedule: Full Time Sign-On Bonus Eligible Remote/Hybrid Regular Apply Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel 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
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
Business Analyst | *Apple* Pay - Banco Popu...
Business Analyst | Apple PayApply now " Apply now + Apply Now + Start applying with LinkedIn Start + Please wait Date:Mar 19, 2024 Location: San Juan-Cupey, PR Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.