Some of the popular game engines available on iOS like cocos2d and Unity come bundled with physics engines so oftentimes the first thought when you want to add a bit of physics to your app is that you need to use one of the fancy game engines you’ve been hearing so much about. In this post I’ll walk you through using the Box2D physics engine without using any game engine or OpenGL.
Let’s start with a simple example. Create a single view iPad application project:
Next we need to setup Box2D. The easiest way to do this is via CocoaPods. CocoaPods greatly simplifies library dependency management for iOS and OS X projects. If you haven’t used it before you need to run the following commands in the terminal to set it up:
Library dependencies are declared in a text file named Podfile which needs to be placed in the same directory as your xcodeproj file. Create the file and paste in the following:
This declares you are targeting iOS and want to use the Box2D library using either version 2.3 or any other minor version up to 2.4 but not including 2.4. If you’re new to CocoaPods I encourage you to read about the other dependency declaration options available.
Final step, point your terminal to your Xcode project’s folder and run
This command will download the Box2D library and in addition create an Xcode workspace that contains your initial project file and a new Pods project where all your dependencies reside. From this point on you should always use the generated workspace instead of the initial project and you’ll be good to go.
Let’s move on to the good stuff and lay out some core Box2D concepts we’ll be using in this tutorial. Box2D simulates interaction between rigid bodies. Bodies have a position and a set of fixtures. Each fixture links a body with a shape and a few physical properties like mass, friction and “bounciness”. All bodies are of course part of a world and you could even have multiple worlds if you’d so desire. There are a host of other features available in Box2D that I won’t be covering in this tutorial. Have a look over the excellent Box2D manual to see what else is available.
Now the great part about Box2D is that it’s completely display agnostic. Its only job is to keep track of your bodies and ensure that everything interacts realistically. This also means it knows nothing of pixels, points or anything like that. Box2D simulates the “real world” and it’s units of measurement are miles, kilograms and seconds. It’s up to you to convert UIKit’s point based coordinates into something Box2D can handle. There’s a catch though: simulating physics on objects of arbitrary size is computationally intensive. To keep things simple Box2D is optimised to handle moving objects of sizes between 0.1 and 10 meters. So considering points and meters equal will not work out very well. Instead we’ll use an arbitrary scaling factor to keep bodies within reasonable size.
Let’s start by declaring a few functions for converting between points to meters and back:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
I also included here two convenience functions for converting between CGPoints and Box2D vectors and back.
Next, open up ViewController.m and replace its contents with the following:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41
The view controller starts by initializing a world object that will handle the interaction with Box2D. The world object is initialized with a frame covering the entire screen. We then create 20 views at random positions on the screen and give them a corner radius to make them look like circles. Finally we pass them to the world object.
Now create a new class called World, do a #import <box2d/Box2D.h> at the top of World.m and add the following ivars to World in the implementation file (which at this point needs to be renamed to World.mm to work with Box2D which is a C++ library):
1 2 3 4
Don’t worry right now about what these objects represent – I’ll talk again about them in the next bits of code. If you never mixed Objective-C and C++ code before, remember that it’s always worth isolating C++ code and imports of C++/Objective-C++ files in implementation files. This saves you the trouble of renaming .m files to .mm when you import your mixed language code and keeps your compile time as low as possible since Objective-C code compiles faster than Objective-C++ code.
Moving on, declare an initialization method initWithFrame:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
This code will setup a Box2D world object with gravity defined to be pointing upwards on the Y axis – meaning objects will appear to be falling from the top to the bottom of our screen. _circle is an array we’ll use to keep track of all the bodies we’ll be adding to our world. Next we’ll create the invisible borders of our screen in createScreenBoundsForFrame: to keep the views from falling off from the screen and finally setup an animation loop to drive everything in setupAniamtionLoop. Here’s the code for createScreenBoundsForFrame:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
Here you can see a screenBounds body object being created. Bodies are always instantiated using the Box2D world object that will also keep track and memory manage them. Also notice how the body is created from a body definition object. This allows multiple bodies to be instantiated using the same defining properties. Next we create a chain shape that spans the left, bottom, right and upper edge of the input frame. This is a special type of shape that doesn’t have a width and is used mostly for defining boundaries. Finally the shape is bounded to the body using a fixture.
Before looking at the animation loop let’s introduce the function that will map UIViews to Box2D bodies:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
Here we create a body with the same position as the view, we add it a circle shape that matches the size of the view and a few physical properties. Later on we’ll need to know what view each body represents so we save the pointer to the view in the body’s user data field.
Let’s move on to setting up the animation loop:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Animations are always computed in discreet time intervals called frames. Animations get more accurate as frames get shorter but since the amount of time required to compute a frame stays relatively constant you take a performance hit when animating in shorter frames. Displays however operate on a fixed frame rate. In the code above, animationLoop: is in charge of animating and drawing a frame on the screen. CADisplayLink is in charge of deciding when the screen is ready to draw something new and will call animationLoop: to do the drawing. It’s entirely possible that animationLoop: would require more time to execute than a single screen refresh cycle, but what CADisplayLink ensures is that your animations stay as smooth as possible with the available resources and that no animation frames are being computed if the display is not ready to show them.
Let’s look at animationLoop: in more detail. First thing it does is figure out how much time has passed since the last run and passes that info to our world object which will then proceed to update its internal state. There are two extra parameters there: velocityIterations and positionIterations. These have more to do with Box2D’s inner workings. What happens is that Box2D approximates body velocity and position in multiple iterations. The more iterations you attempt, the more realistic the outcome. You can fine tune these values until you find something acceptable in terms of performance and realism.
Once Box2D does its thing, all we need to do is iterate over all circle bodies and update the position of their associated UIView to match the bodies’ new positions.
Finally, we need to take care of the cleanup. The only C++ object we allocated ourselves is the world object. Everything else was allocated internally by Box2D and will be cleaned up once the world object is destroyed:
1 2 3 4
That’s it! If you followed all the steps you should end up with something like this:
You can grab the full code for this tutorial from here: https://github.com/MihaiDamian/Box2DTutorial
So there you have it. Physics engines can be used very easily in a UIKit based app. In fact you could even go and build a game like Hundreds using nothing but UIKit and Box2D.