Graphics Reference
In-Depth Information
Figure 11.1 A crate image, falling due to simulated gravity
Adding User Interaction
The next step is to add an invisible wall around the edge of the view so that the crate
doesn't fall off the bottom of the screen. You might think that we would implement this
with another rectangular cpPolyShape , like we used for our crate, but we want to detect
when our crate leaves the view, not when it is colliding with it, so we need a hollow
rectangle, not a solid one.
We can implement this by adding four cpSegmentShape objects to our cpSpace .
( cpSegmentShape represents a straight line segment, so four of them can be combined to
form a rectangle.) We will attach these to the space's staticBody property (an immovable
body that is not affected by gravity) instead of a new cpBody instance as we did with each
crate, because we do not want the bounding rectangle to fall off the screen or be dislodged
when hit by a falling crate.
We'll also add a few more crates so they can interact with one another. Finally, we'll add
accelerometer support so that tilting the phone adjusts the gravity vector. (Note that to test
this you will need to run on a real device because the simulator doesn't generate
accelerometer events, even if you rotate the screen.) Listing 11.4 shows the updated code,
and Figure 11.2 shows the result.
Because our example is locked to landscape mode, we've swapped the x and y values for
the accelerometer vector. If you are running the example in portrait mode, you will need to
swap them back to ensure the gravity direction matches up with what's displayed on the
screen. You'll know if you get it wrong; the crates will fall upward or sideways!
Search WWH ::




Custom Search