Graphics Reference
In-Depth Information
If the time step is not set to a fixed, precise value, the physics simulation will not be
deterministic. This means that given the same exact inputs it may produce different
results on different occasions. Sometimes this doesn't matter, but in a physics-based
game, players might be confused when the exact same actions on their part lead to
different outcomes. It also makes testing more difficult.
A skipped frame due to a performance glitch or an interruption like a phone call
might cause incorrect behavior. Consider a fast-moving object like a bullet: Each
frame, the simulation will move the bullet forward and check for collisions. If the
time between frames increases, the bullet will move further in a single simulation step
and may pass right through a wall or other obstacle without ever intersecting it,
causing the collision to be missed.
What we ideally want is to have short fixed time steps for our physics simulation, but still
update our views in sync with the display redraw (which may be unpredictable due to
circumstances outside our control).
Fortunately, because our models (in this case, the cpBody objects in our Chipmunk
cpSpace ) are separated from our views (the UIView objects representing our crates
onscreen), this is quite easy. We just need to keep track of the simulation step time inde-
pendently of our display frame time, and potentially perform multiple simulation steps for
each display frame.
We can do this using a simple loop. Each time our CADisplayLink fires to let us know the
frame needs redrawing, we make a note of the CACurrentMediaTime() . We then advance
our physics simulation repeatedly in small increments (1/120th of a second in this case)
until the physics time catches up to the display time. We can then update our views to
match the current positions of the physics bodies in preparation for the screen refresh.
Listing 11.5 shows the code for the fixed-step version of our crate simulation.
Listing 11.5 Fixed Time Step Crate Simulation
#define SIMULATION_STEP ( 1 / 120.0 )
- ( void )step:( CADisplayLink *)timer
{
//calculate frame step duration
CFTimeInterval frameTime = CACurrentMediaTime ();
//update simulation
while ( self . lastStep < frameTime)
{
cpSpaceStep ( self . space , SIMULATION_STEP);
self . lastStep += SIMULATION_STEP;
}
Search WWH ::




Custom Search