Game Development Reference
In-Depth Information
This is an example of a property that can be read from and written to. You add a
color
property to
all the colored game-object types:
Cannon
,
Ball
, and
PaintCan
. The only difference in the code in the
get
and
set
parts is the sprites used to represent the colors. For example, this is the
color
property
of the
Ball
class:
Object.defineProperty(Ball.prototype, "color",
{
get: function () {
if (this.currentColor === sprites.ball_red)
return Color.red;
else if (this.currentColor === sprites.ball_green)
return Color.green;
else
return Color.blue;
},
set: function (value) {
if (value === Color.red)
this.currentColor = sprites.ball_red;
else if (value === Color.green)
this.currentColor = sprites.ball_green;
else if (value === Color.blue)
this.currentColor = sprites.ball_blue;
}
});
Because you've defined these properties, you can now change the color of the ball depending on
the color of the cannon very easily, in a single line of code:
this.color = Game.gameWorld.cannon.color;
Look at the Painter7 example to see how and where it uses properties to make the code easier to
read. For some programmers, properties may look odd at first because they're used to getter and
setter methods. However, properties do make more intuitive sense. They're a great way to reduce
the complexity of lines of code.
Handling Collisions between the Ball and the Cans
The Painter7 example extends the game by handling collisions between the ball and the cans. If two
objects collide, you have to handle this collision in the
update
method of one of the two objects. In this
case, you can choose to handle collisions in the
Ball
class or in the
PaintCan
class. Painter7 handles
the collision in the
PaintCan
class, because if you were to do it in the
Ball
class, you would need to
repeat the same code three times, once for each paint can. By handling collisions in the
PaintCan
class,
you get this behavior automatically, because each can checks for itself whether it collides with the ball.
Although collision checking can be done in many different ways, you use a very simple method
here. You define that there is a collision between two objects if the distance between their centers
is smaller than a certain value. The position of the center of the ball at any time in the game world is
computed by adding the center of the ball sprite to the position of the ball. You can calculate
the center of a paint can in a similar way. Because you added a few nice properties to calculate
Search WWH ::
Custom Search