HTML and CSS Reference
In-Depth Information
render()
Makes the
x
and
y
properties for each ball equal to
nextx
and
nexty
respectively,
and then draws them to the canvas.
And here is the code:
function drawScreen () {
update();
testWalls();
collide();
render();
}
Updating positions of objects
The
update()
function loops through all the balls in the
balls
array, and updates the
nextx
and
nexty
properties with the
x
and
y
velocity for each ball. We don't directly
update
x
and
y
here, because we want to test collisions against walls and other balls
before they occur. We will use the
nextx
and
nexty
properties for this purpose:
function update() {
for (var i = 0; i <balls.length; i++) {
ball = balls[i];
ball.nextx = (ball.x += ball.velocityx);
ball.nexty = (ball.y += ball.velocityy);
}
}
Better interaction with the walls
We discussed the interactions between balls and walls in the last example, but there is
still one issue. Since we move the balls by the
x
and
y
location of their center, the balls
would move halfway off the canvas before a bounce occurred. To fix this, we add or
subtract the
radius
of the
ball
object, depending on which walls we are testing. For
the right side and bottom of the canvas, we add the radius of the ball when we test the
walls. In this way, the ball will appear to bounce exactly when its edge hits a wall.
Similarly, we subtract the radius when we test the left side and the top of the canvas,
so that the ball does not move off the side before we make it bounce off a wall:
function testWalls() {
var ball;
var testBall;
for (var i = 0; i <balls.length; i++) {
ball = balls[i];
if (ball.nextx+ball.radius > theCanvas.width) {
ball.velocityx = ball.velocityx*−1;
ball.nextx = theCanvas.width - ball.radius;