Introduction to physics on the iPhone using Box2d and Cocos2D

What we're going to cover in this tutorial

In this tutorial I'm going to demonstrate how to set up the physics demo shown above using Cocos2D, Box2D and Shape Workshop. You'll learn how to install Cocos2D for XCode, how to create a new Box2D enabled project, how to trace and triangulate images using Shape Workshop and finally how to export the images into your scene. So let's get started with: Part 1: Setting up Cocos2D for XCode.


Shape Workshop level designer for iPhone and Android

Update: 3/10/2012

Shape Workshop 2.0 coming soon! Read more here

Download Shape Workshop Here

Over the last few months I've been working on a 2D level builder for iPhone and Android. I'm excited to say that I'll be starting the public beta testing phase this week. The program provides a huge amount of functionality and makes designing 2D levels really easy.

If you're interesting in helping with the beta testing you can sign up at the bottom of the page. When the beta's released I'll notify you by email. The beta will be limited so if you're interested, sign up before it becomes full. Any beta tester who submits at least one bug report will get a pro license half price and anyone who submits 4 or more bug reports will get the license for free!

So what's so great about Shape Workshop?

There's nothing on the market which comes close to Shape Workshop in flexibility or power. Here are the core features:


iPhone - Saving game or app state using NSUserDefaults

In this article I'm going to explain how to store complex game or app data using the NSUserDefaults object in iOS. User defaults is ideal for storing structured information like: game state, high scores, game progress information. If you need to store unstructured information which you will be accessing by using SQL queries then you should use a built in database instead.

NSUserDefaults is the standard way of persisting data on the iPhone or iPad - much like Preferences API in Java. It stores the data in a .plist file in a safe directory. This is good for three reasons. First, your data will not be deleted when the app is updated. Second, your data will automatically be backed up during a synch with iTunes. Third, .plist is a tried and tested format which will not change. This means that an upgrade to iOS can't mess up your saved data. For more information look here.

Because user defaults uses a .plist file only certain data types are supported:

  • NSString
  • NSNumber
  • NSData
  • NSDate
  • NSArray
  • NSDictionary

As long as your data is stored in one of these formats it will be supported by NSUserDefaults. Lots of problems are caused by people trying to save incompatible objects. It is also possible to encode objects and store them in a NSData object as I'll show later.

Saving data with NSUserDefaults

Saving and retrieving data is very straightforward. The easiest way to think about this is to treat the NSUserDefaults object like an NSMutableDictionary which persists between App runs because this is exactly what it is. A standard NSMutableDictionary is stored in RAM which is cleared down when the app closes. With NSUserDefaults however, the system automatically writes the dictionary from RAM to a .plist file when the app closes. When the app opens again the system writes the .plist file to RAM again. With this in mind, using NSUserDefaults is very logical. Get a pointer to the dictionary and add some information. When you want to retrieve the information, get another pointer and read the information!

In this example I'll save a series of data types:


What is a game engine?

In this article I'm going to explain what a game engine is and why it's useful. When I first started game design many terms confused me. I heard: game engine, sprite, game loop, physics engine, Cocos2D... I had a rough idea of what they were but not how the concepts fitted together. With the benefit of the experience I now have, I'm going to explain what all this things mean and how they fit together. This guide is designed for people who are new to game design and will focus and iPhone and Android operating systems. I'll also give an overview of my favorite game engines for each platform.

How a game works

Games can range from simple to extremely sophisticated but at the most basic level every game performs the same core functions. All games take inputs from the user, using those inputs they work out what effect it has had on the game state, finally they display or animate something on the screen. After this, the process is repeated until you either win or fail. Lets take the example of Angry Birds for iPhone. The game starts by setting up an initial game state. In this case it gives you a certain number of birds and a pile of wood and pigs to destroy. At this point the game waits for input. If you don't do any thing the game just stays as it is. When you touch the screen and pull back the catapult the game is responding to your input and changing the game state accordingly i.e. the postion of the catapult. When you let go the game keeps going and calculates what will happen. The bird collides with the structure and the wood responds realistically. When everything has stopped moving the score is calculated and the game is over.

This is simple enough but how could we go about coding this? In programming terms, when we want the computer to repeat something over and over again we use a loop. For games this is called the game loop. Inside the loop we perform all the things we need to do to make the game work. We listen for inputs, calculate how those inputs affect the game state and finally update the screen so that it correctly displays the game state. Below is a simple representation of the loop:


Re-using particle emitters in Cocos2D

I'm currently working on a Cocos2D game which uses a lot of particles. Several times a second an explosion is triggered an every three seconds the background particle emitter changes. When I first coded the game I wasn't worrying about optimisation so I just loaded the CCParticleSystems from file each time I needed them. Now that I'm nearing completion, I've been looking at optimisation. When I profiled my game using Instruments, by checking allocations, I noticed that my emitters were causing a horrible memory leak. My game would start off running at a snappy 60 fps. After sever minutes the frame rate had dropped to 50 fps then 40, 30... No leak showed in the leaks section of Instruments so I checked the allocations panel. Here I could see the number of active CCParticleSystems continuously creeping up and up. After several minutes there would be 700 living particle systems using about 15mb of memory. Although I used the

  1. [system autoRemoveOnFinish]

method which is available for CCParticleSystems it seemed that the particle systems weren't being correctly released. After some looking around on the internet saw a suggestion to use an @autorelease pool. Although this solved my memory leak it didn't seem like the most efficient solution - I was still loading hundreds of emitters from file every minute. By looking at the CCParticleSystem source code you can see that the process of loading a new emitter from file is complex and calling it a lot has a real impact on game performance. I decided to create a ParticleManager class to allow me to pool and re-use my emitters.

Creating a Particle Manager class to re-use emitters

This class is fairly simple and gave my game a major boost in performance.


HTML div box not containing floating elements

Today I was doing some web design for one of my clients and I came across a frustrating problem. I wanted to provide a white background for a block of floating text. I setup a div container outside the text with a background colour set to white but the div container didn't contain the text. It appeared to have zero height. I could set the height manually in pixels but I needed the div to expand automatically to contain it's child elements.

Eventually after a bit of searching I found that a div will not automatically contain floating elements. To force it to do this you have to include the following code in your CSS file:

  1. .div-class { overflow: auto; }

Hope this saves someone some frustration!


CoreAudio Mixers and Master volume control

My general experience of CoreAudio on iOS is that it's logically put together and very powerful however woefully lacking in documentation. Even the simplest thing can take a morning of searching the internet to work out. I've decided to blog about the issues I come across to try to help save people time in the future.

In this post I'm going to explain how to set up a mixer to mix a number of CoreAudio channels to one output module. Then, how to change the output volume of the mixer.

Setting up a Mixer

I'm not going to go into the whole process of setting up an AUGraph. If you need to know how to do this you can refer to the tutorial I wrote about CoreAudio and MIDI. The first step in the process is to set up the componentManufacturer, componentType and componentSubType for the new mixer AudioUnit.


How to Make a Successful iPhone Game

In this article, I'm going to cover in detail, how to make a game which is addictive and fun. In short, a game which will make you money.

Why do we play?

Why do people spend a large portion of their time knocking over pigs with birds or drawing pictures to represent words. Time is scarce and valuable, yet people spend a huge amount of it playing games. The reason, is that good games tap into fundamental elements of human nature which are difficult to realize in the real world. Take rock band for as an example, rock band is an instrument simulator which essentially simplifies the playing of an instrument. In real life, it takes years of practice and dedication to be able to play an instrument well. I only really started to enjoy playing the piano after 3 years. Those three years were huge time investment with little reward. With Rock Band however, you can play an instrument straight away! You can get all the enjoyment and satisfaction of playing an instrument without the effort. Reward with minimal effort. All good games have an element of real life. The difference it that they alter the learning curve to make the game more accessible than real life. In the following sections I'm going to cover four main elements which I believe should be the tenants of game design: completion, collection, improvement and competition.


Cocos2D drawing a custom filled polygon

In this article I'm going to explain how to draw custom polygons using Cocos2D and OpenGL. Cocos2D has the capability to draw primative polygons using the ccDrawPrimative class. This however comes with some limitations:

  • It is not possible to draw filled polygons
  • The functions are primative OpenGL commands which means that you can't take advantage of Cocos2D's node actions

To get around this I've written a PolygonNode class. This extends Cocos2D's node object and allows you to create nodes which contain custom polygons.


Useful CoreMIDI and CoreAudio Links

Here's a list of useful CoreMIDI and CoreAudio resource I've come across while writing my current iOS application.

There are a surprising number of example projects available involving CoreAudio. The problem is that they're hard to find. When I first searched I found hardly anything. After several days of digging I had a large amount of reference material.



Subscribe to RSS - blogs