Game Development Reference
In-Depth Information
Writing a Class with Multiple Instances
Now that you can construct multiple objects of the same type, let's add a few paint cans to the
Painter game. These paint cans should be given a random color, and they should fall down from
the top of the screen. Once they have fallen out of the bottom of the screen, you assign a new color
to them and move them back to the top. For the player, it seems as though different paint cans are
falling each time. Actually, you need only three paint-can objects that are reused. In the PaintCan
class, you define what a paint can is and what its behavior is. Then, you can create multiple
instances of this class. In the PainterGameWorld class, you store these instances in three different
member variables, which are declared and initialized in the PainterGameWorld constructor:
function PainterGameWorld() {
this.cannon = new Cannon();
this.ball = new Ball();
this.can1 = new PaintCan(450);
this.can2 = new PaintCan(575);
this.can3 = new PaintCan(700);
}
A difference between the PaintCan class and the Ball and Cannon classes is that paint cans have
different positions. This is why you pass along a coordinate value as a parameter when the paint
cans are constructed. This value indicates the desired x-position of the paint can. The y-position
doesn't have to be provided, because it will be calculated based on the y-velocity of each paint can.
In order to make things more interesting, you let the cans fall with different, random velocities.
(How you do that is explained later in this chapter.) In order to calculate this velocity, you want to
know the minimum velocity a paint can should have, so it doesn't fall too slowly. To do this, you add
a member variable minVelocity that contains the value. As a result, this is the constructor of the
PaintCan class:
function PaintCan(xPosition) {
this.currentColor = sprites.can_red;
this.velocity = new Vector2();
this.position = new Vector2(xPosition, -200);
this.origin = new Vector2();
this.reset();
}
Just like the cannon and the ball, a paint can has a certain color. By default, you choose the red
paint-can sprite. Initially, you set the y-position of the paint can such that it's drawn just outside the
top of the screen, so that later in the game, you can see it fall. In the PainterGameWorld constructor,
you call this constructor three times to create the three PaintCan objects, each with a different
x-position.
Because the paint cans don't handle any input (only the ball and the cannon do this), you don't need
a handleInput method for this class. However, the paint cans do need to be updated. One of the
things you want to do is to have the paint cans fall at random moments and at random speeds. But
how can you do this?
 
Search WWH ::




Custom Search