Game Development Reference
In-Depth Information
Creating the Paddle and Puck
Directly above the message board will be the floor for the paddle and represent the bottom bounds of the board where
the puck can pass through. Let's draw those game elements next (see Listing 4-8).
Listing 4-8. Drawing and Adding the Paddle and Puck
function buildPaddle() {
paddle = new createjs.Shape();
paddle.width = PADDLE_WIDTH;
paddle.height = 20;
paddle.graphics.beginFill('#3e6dc0').drawRect(0, 0, paddle.width, paddle.height);
paddle.nextX = 0;
paddle.x = 20;
paddle.y = canvas.height - paddle.height - SCORE_BOARD_HEIGHT;
stage.addChild(paddle);
}
function buildPuck() {
puck = new createjs.Shape();
puck.graphics.beginFill('#FFFFFF').drawRect(0, 0, 10, 10);
puck.width = 10;
puck.height = 10;
puck.x = canvas.width - 100;
puck.y = 160;
puck.velX = PUCK_SPEED;
puck.velY = PUCK_SPEED;
puck.isAlive = true;
stage.addChildAt(puck, 0);
}
The game paddle is drawn and positioned appropriately by using the board's height and y position, as well as
its own height. The puck is then drawn in the following function and positioned near the center of the stage. You
then assign it some properties to determine its velocity, and if it is currently in play. Its velocity determines how fast
it should travel and in what direction it should move. By assigning both velX and velY to positive values, it will begin
to travel right and down by an increase of the PUCK_SPEED value on every game tick. Lastly, the addChildAt method is
used to add it to the bottom layer of the stage. This is to ensure that the puck will travel under the scoreboard when it
flies out of bounds beneath the floor.
Adding the Controls
To add interactivity to the game, you need to set up the keyboard event listeners to move the paddle, and to both
pause and start the game. Listing 4-9 shows the registering and handling of these event listeners.
Listing 4-9. Setting Up the Game Controls
function setControls() {
window.onkeydown = handleKeyDown;
window.onkeyup = handleKeyUp;
}
 
Search WWH ::




Custom Search