Graphics Reference
In-Depth Information
including an “indie” version with Objective-C bindings. The plain C version is free, though,
so that's what we will use for this example. Version 6.1.4 is the latest at the time of writing;
you can download it from http://chipmunk-physics.net.
The Chipmunk physics engine as a whole is quite large and complex, but we will be using
only the following classes:
cpSpace —This is the container for all of the physics bodies. It has a size and
(optionally) a gravity vector.
cpBody —This is a solid, inelastic object. It has a position in space and other physical
properties such as mass, moment, coefficient of friction, and so on.
cpShape —This is an abstract geometric shape, used for detecting collisions. Multiple
shapes may be attached to a body, and there are concrete subclasses of cpShape to
represent different shape types.
In our example, we will model a wooden crate that falls under the influence of gravity. We
will create a Crate class that encompasses both the visual representation of the crate
onscreen (a UIImageView ) and the physical model that represents it (a cpBody and
cpPolyShape , which is a polygonal cpShape subclass that we will use to represent the
rectangular crate).
Using the C version of Chipmunk introduces some challenges because it doesn't support
Objective-C's reference counting model, so we need to explicitly create and free objects.
To simplify this, we tie the lifespan of the cpShape and cpBody to our Crate class by
creating them in the crate's -init method and freeing them in -dealloc . The configuration
of the crate's physical properties is fairly complex, but it should make sense if you read the
Chipmunk documentation.
The view controller will manage the cpSpace , along with the timer logic as before. At each
step, we'll update the cpSpace (which performs the physics calculations and repositions all
the bodies in the world) and then iterate through the bodies and update the positions of our
crate views to match the bodies that model them. (In this case, there is actually only one
body, but we will add more later.)
Chipmunk uses an inverted coordinate system with respect to UIKit (the Y axis points
upward). To make it easier to keep our physics model in sync with our view, we'll invert
our container view's geometry using the geometryFlipped property (mentioned in Chapter
3) so that model and view are both using the same coordinate system.
The code for the crate example is shown in Listing 11.3. Note that we aren't freeing the
cpSpace object anywhere. In this simple example, the space will exist for the duration of
the app lifespan anyway, so this isn't really an issue but in a real-world scenario, we should
really handle this in the same way we do with the crate body and shape, by wrapping it in
standalone Cocoa object and using that to manage the Chipmunk object's lifecycle. Figure
11.1 shows the falling crate.
Search WWH ::




Custom Search