Game Development Reference
In-Depth Information
public void run() {
updatePhysics();
/**
* Cause an invalidate to happen on a subsequent cycle
* through the event loop. Use this to invalidate the View
* from a non-UI thread. onDraw will be called sometime
* in the future.
*/
postInvalidate();
}
}
/**
* A timer is used to move the sprite around
*/
protected void startUpdateTimer() {
mUpdateTimer = new Timer();
mUpdateTimer.schedule(new UpdateTask(), 0, mPeriod);
}
protected void stopUpdateTimer() {
if (mUpdateTimer != null) {
mUpdateTimer.cancel();
}
}
/**
* Set the update period
*
* @param period
*/
public void setUpdatePeriod(long period) {
mPeriod = period;
}
When the layout initializes, the onLayout() method will fire and call initialize() and
startUpdateTimer() . These methods will start the Timertask:run() method, which updates the physics
of the child class and invalidates the view by calling postInvalidate() . Invalidating the view will, in turn,
tell the system UI thread to refresh the display. This cycle will repeat itself until the value of the update
period ( mPeriod ) is reached, and this value can be set by the main class ( SpaceBlaster ) using the
setUpdatePeriod method. In this way, we have created a simple refresh loop for the game.
Implementing the Game
The previous sections showed you the foundation for the main class, SpaceBlasterGame . Here is where all
the meat resides. Let's take a closer look at the most important sections of SpaceBlaster.java . Note that
the class has been stripped for simplicity in Listing 3-5, but the chapter source contains the full
implementation.
Search WWH ::




Custom Search