Game Development Reference
In-Depth Information
In the update method of the ball, you need to retrieve the current color of the cannon so you can
update the ball's color. Here is how you did this in the previous chapter:
if (cannon.currentColor === sprites.cannon_red)
ball.currentColor = sprites.ball_red;
else if (cannon.currentColor === sprites.cannon_green)
ball.currentColor = sprites.ball_green;
else
ball.currentColor = sprites.ball_blue;
When defining a class using the JavaScript prototype approach, you have to replace ball with this
(because there is no named instance of an object). So the previous code is translated to
if (cannon.currentColor === sprites.cannon_red)
this.currentColor = sprites.ball_red;
else if (cannon.currentColor === sprites.cannon_green)
this.currentColor = sprites.ball_green;
else
this.currentColor = sprites.ball_blue;
But how do you refer to the cannon object if cannons are also constructed using a class? This raises
two questions:
Where in the code are game objects constructed?
How do you refer to these game objects if they aren't global variables?
Logically, game objects should be constructed when the game world is constructed. This is why
the Painter5 example creates the game objects in the PainterGameWorld class (which before was the
painterGameWorld object). Here is part of the constructor of that class:
function PainterGameWorld() {
this.cannon = new Cannon();
this.ball = new Ball();
// create more game objects if needed
}
So, this answers the first question, but it raises another question. If game objects are created when
the game world is created, where do you call the constructor of PainterGameWorld to create the
game world? If you open the Game.js file, you see that there is yet another class defined using the
prototype approach: Game_Singleton . This is its constructor:
function Game_Singleton() {
this.size = undefined;
this.spritesStillLoading = 0;
this.gameWorld = undefined;
}
 
Search WWH ::




Custom Search