Game Development Reference
In-Depth Information
"...--........W.--...",
"r..W........--.W....",
"...--..........--...",
"....W...........W..R",
"...--..........--...",
".1..................",
"######..####..######"]
});
A lowercase r means the rocket should fly from left to right, and an uppercase R means it should fly
from right to left (see also Table 24-1).
Creating and Resetting the Rocket
Let's create a Rocket class that represents this particular kind of enemy. You inherit from the
AnimatedGameObject class, because the rocket is animated. In the constructor, you initialize the
Rocket object. You need to load the rocket animation and play it, and then you need to check
whether the animation should be mirrored. Because the animation has the rocket moving to the right,
you need to mirror it if the rocket moves to the left. You also store the starting position of the rocket
so you can place it back at that position when it moves out of the screen. Finally, you need a variable
spawnTime to keep track of when the rocket should appear. This is the complete constructor:
function Rocket(moveToLeft, startPosition, layer, id) {
powerupjs.AnimatedGameObject.call(this, layer, id);
this.spawnTime = 0;
this.startPosition = startPosition;
this.mirror = moveToLeft;
this.loadAnimation(sprites.rocket, "default", true, 0.5);
this.playAnimation("default");
this.origin = new powerupjs.Vector2(this.width / 2, this.height);
this.reset();
}
The last instruction in the constructor is a call to the reset method. In this method, you set the
current position of the rocket to the starting position, you set the visibility to false (so the rocket
is initially invisible), and you set its velocity to zero. You also use the random number generator to
calculate a random time (in seconds) after which the rocket should appear and start moving. You
store this time in the member variable spawnTime . You put these instructions in a separate reset
method because you call this method later as well, after the rocket has flown out of the screen.
Programming the Rocket Behavior
The behavior of the rocket is (as usual) encoded in the update method. Basically, a rocket exhibits
two main types of behavior: either it's visible and moving from one end of the screen to the other,
or it's invisible and waiting to appear. You can determine which of the two states the rocket is in 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 less than or equal to zero, the rocket is visible and
moving from one end of the screen to the other.
 
Search WWH ::




Custom Search