HTML and CSS Reference
In-Depth Information
left wall as opposed to the right wall. For that, you need to use separate if statements, and you see an
example of that when screen wrapping, coming up shortly.
But there is a small problem that may cause things to look wrong. Take a look at Figure 6-1.
Figure 6-1. This ball isn't fully off the canvas, but it will be removed.
In Figure 6-1, you can see that the ball's position, as determined by its x and y coordinate in the center, is
past the right edge of the screen, so it will be removed. If the ball is moving fast enough, you might not
notice. But if it's moving slowly—like a pixel per frame—it will ease off the edge of the canvas. When it
gets halfway, it will vanish from the screen and ruin the illusion.
To fix this, the ball should be all the way out of the area before removing it. To do this, you must take the
object's width into account. And because the position is in the center of a circle, you need to worry about
half of its width, which is stored in the radius property defined in our Ball class. The if statement needs
to become a bit more complex, so it will change to something like this:
if (ball.x - ball.radius > canvas.width ||
ball.x + ball.radius < 0 ||
ball.y - ball.radius > canvas.height ||
ball.y + ball.radius < 0) {
balls.splice(balls.indexOf(ball), 1);
}
The changes are demonstrated in Figure 6-2.
ball . x
ball . x
-ball . width / 2
Figure 6-2. This ball is completely off the canvas and can be safely removed.
Although this particular example uses a ball, or round object, the same boundary check should work for
any shape, as long as the position coordinate of the object is in the center.
 
Search WWH ::




Custom Search