Game Development Reference
In-Depth Information
The current position of the ball is updated by adding the velocity to its x and y components. Here are
the instructions that do this:
ball.position.x = ball.position.x + ball.velocity.x * delta;
ball.position.y = ball.position.y + ball.velocity.y * delta;
As you can see, this is where the delta variable is used. You calculate the new position of the ball
based on the velocity and the time that has passed since the last update. You multiply each velocity
dimension with the value in the delta variable, and you add the result to the current position of
the ball. That way, if you ever decide to use a higher or lower frame rate, the speed at which game
objects move will not change.
Note In the old days, computers were so slow that the concept of a fixed timestep didn't exist. Game
developers assumed that everyone would be playing their game on an equally slow machine, so they called
the game-loop methods as often as possible and simply updated the position of an object with a constant
velocity factor. As a result, when computers became faster, these games became more and more difficult to
play! Players don't like this. Therefore, always take the elapsed time into account when calculating things like
velocities and positions.
If the ball isn't currently shooting, you're allowed to change its color. In this case, you do that by
retrieving the current color of the cannon and changing the color of the ball accordingly. That way,
you're sure the color of the ball always matches the color of the cannon. You need an if instruction
to handle the different cases, as follows:
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;
You also update the position of the ball:
ball.position = cannon.ballPosition();
ball.position.x = ball.position.x - ball.currentColor.width / 2;
ball.position.y = ball.position.y - ball.currentColor.height / 2;
Why do you change the position? When the ball isn't in the air, the player can modify its shooting
position by rotating the barrel of the cannon. Therefore, you need to calculate the correct ball
position here, to ensure that it matches the current orientation of the cannon barrel. In order to do
this, you add a new method called ballPosition to cannon , in which you calculate the position of
 
Search WWH ::




Custom Search