Game Development Reference
In-Depth Information
The Ball Class
You define the new
Ball
class in a fashion very similar to the
Cannon
class. Just as in the
Cannon
class, you inherit from the
ThreeColorGameObject
class. The only difference is that you have to add
an extra member variable that indicates whether the ball is currently shooting:
function Ball() {
ThreeColorGameObject.call(this, sprites.ball_red, sprites.ball_green,
sprites.ball_blue);
this.shooting = false;
this.reset();
}
Ball.prototype = Object.create(ThreeColorGameObject.prototype);
When a
Ball
instance is created, you need to call the
ThreeColorGameObject
constructor, just as you
did with the
Cannon
class. In this case, you pass along the ball sprites as parameters. In addition,
you need to give the
shooting
variable an initial value of
false
, and you reset the ball by calling the
reset
method.
The
Ball
class clearly illustrates what happens when you inherit from another class. Each
Ball
instance consists of a part that has been inherited from
ThreeColorGameObject
and a part that is
defined in the
Ball
class. Figure
11-2
shows what the memory looks like for a
Ball
object without
using inheritance. Figure
11-3
also shows a
Ball
instance, but using the inheritance mechanism
introduced in this chapter.
Ball
Vector2
position
false
shooting
x
0
y
0
Vector2
velocity
x
0
y
0
Vector2
origin
x
0
y
0
...
currentColor
Figure 11-2.
Overview of the memory used by an instance of the
Ball
class (no inheritance)
Search WWH ::
Custom Search