Game Development Reference
In-Depth Information
28.2.2 Programming the Rocket Behavior
The behavior of the rocket is (as usual) encoded in the Update method. Basically,
there are two main types of behavior that a rocket exhibits. Either the rocket is
visible and moving from one end of the screen to the other end, or the rocket is
invisible and waiting to appear. We can determine in which of the two states we are
by looking at the value of the spawnTime variable. If this variable contains a value
larger than zero, the rocket is waiting to be spawned. If the value is smaller than or
equal to zero, the rocket will be visible and moving from one end of the screen to
the other.
Let us first look at the first case. If the rocket is waiting to be spawned, we simply
subtract the time that was elapsed since the last Update call from the spawn time:
if (spawnTime > 0)
{
spawnTime
= gameTime.ElapsedGameTime.TotalSeconds;
return ;
}
The second case is slightly more complicated. In the second case, we are moving
from one end of the screen to the other. So, we set our visibility status to true ,we
calculate our velocity depending on the direction we are moving in, and we update
our position:
this .Visible = true ;
this .velocity.X = 600;
if (Mirror)
this .velocity.X
= 1f;
Finally, we have to check if the rocket has flown outside of the screen. If that is
the case, the rocket is reset. We check if the rocket is outside of the screen using
bounding boxes. If the bounding box enclosing the screen does not intersect the
rocket bounding box, we know that the rocket is outside of the screen, and we reset
it:
Rectangle screenBox = new Rectangle(0, 0, GameEnvironment.Screen.X,
GameEnvironment.Screen.Y);
if (!screenBox.Intersects( this .BoundingBox))
this .Reset();
This completes the Rocket class, except for the interaction with the player, which is
something we will look at in more detail in the following chapter. For the complete
class, see Listing 28.1 .
Search WWH ::




Custom Search