Game Development Reference
In-Depth Information
between different logic during gameplay (which is most of them), a
state machine will become the backbone of your application. Here
are the steps you go through to set up the state machine we
'
ll be
using in this chapter:
1. Define all the states your game will need to use, each with a
unique integer identifier (in the case of the air hockey game, I
'
ll
make use of four discrete states).
2. Create event handlers for the logic that needs to happen in each
state. There are three components to every state:
a. ENTER: This event occurs once when a state is switched to
from another state.
b. UPDATE: This event occurs repetitively (usually on a frame
cycle) as long as the machine stays in this state.
c. EXIT: This event occurs when a call is made to the machine
to switch to a new state; this is usually reserved for doing
cleanup from the state being left.
3. Create a new instance of the state manager class and add each
of the states to it.
4. On an ENTER_FRAME loop or similarly timed event, call the
update method of the state machine.
Some of this will make more sense when we look at how it is
actually implemented in the game, which we
ll get to shortly. In
the meantime, suffice it to say that in practice, it is very simple to
set up and provides the most flexibility for adding new states or
changing the flow between states throughout development. There
'
'
s
a reason we use it on a daily basis!
Physics Simulation with Box2D
In Chapter 11, we took a look at some elementary physics princi-
ples that we will use commonly in games. In Chapters 14 and 15,
we implemented some very basic physics using simple collision
detection and gravity. However, in this example, a little more is
required. If you
ll know that the
puck ricochets off the two-player paddles, as well as the walls.
Gravity and friction are abated by the presence of upward blowing
air. We could write our own physics simulation to recreate all this,
but I
'
ve ever played air hockey, you
'
m not going to, favoring instead to use the very popular,
open-source Box2D library that has been ported to just about every
platform imaginable. I
'
'
m doing this for two reasons:
￿
Don
t re-invent the wheel. There are some cases in which
rolling your own physics is the best way to go because it will
have the lightest memory or processor overhead. We used a
custom system in Marble Runner in Chapter 15 because on the
iPhone, every single cycle was counted and it was more
important to be efficient than robust. On the Android, we
'
'
ve got