Game Development Reference
In-Depth Information
Inside ball.update , you need to define the ball's behavior. This behavior is different depending on
whether the ball is currently shooting. This is the complete method:
ball.update = function (delta) {
if (ball.shooting) {
ball.velocity.x = ball.velocity.x * 0.99;
ball.velocity.y = ball.velocity.y + 6;
ball.position.x = ball.position.x + ball.velocity.x * delta;
ball.position.y = ball.position.y + ball.velocity.y * delta;
}
else {
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;
ball.position = cannon.ballPosition();
ball.position.x = ball.position.x - ball.currentColor.width / 2;
ball.position.y = ball.position.y - ball.currentColor.height / 2;
}
if (painterGameWorld.isOutsideWorld(ball.position))
ball.reset();
};
As you can see in the header of this method, it has one parameter called delta . This parameter is
necessary because in order to calculate what the new position of the ball should be, you need to
know how much time has passed since the previous call to update . This parameter might also be
useful in the handleInput method of some game objects—for example, if you want to know the
speed at which the player is moving the mouse, then you need to know how much time has passed.
The Painter4 example extends every object that has game-loop methods ( handleInput , update , draw )
such that the time passed since the last update is passed along as a parameter.
But where do you calculate the value of delta? And how do you calculate it? In the example, you do
this in the Game.mainLoop method:
Game.mainLoop = function () {
var delta = 1 / 60;
Game.gameWorld.handleInput(delta);
Game.gameWorld.update(delta);
Canvas2D.clear();
Game.gameWorld.draw();
Mouse.reset();
requestAnimationFrame(Game.mainLoop);
};
Because you want the game loop to be executed 60 times per second, you calculate the delta value
as follows:
var delta = 1 / 60;
Search WWH ::




Custom Search