HTML and CSS Reference
In-Depth Information
// do something
}
if (ball.y > canvas.height) {
// do something
} else if (ball.y < 0) {
// do something
}
Stepping through these boundary checks, if the ball's x position is greater than the right edge, or
canvas.width , then it is too far to the right. There's no way it can also be past the left edge going the
other way, which is 0—so you don't need to check that. You need to check the left position only in the case
that the first if fails. Do the same for the top and bottom by checking the ball's y position against the
canvas.height . However, it is possible for the object to be out of bounds on the x and y axis at the same
time, so keep those two checks separate.
But what are you supposed to do when the object goes out of bounds? You learn about these four options:
Remove it.
Bring it back into play as if it were a brand-new object (regeneration).
Wrap it back onto the screen, as if it were the same object reappearing at a different location.
Have it bounce back into the area.
Let's start with simple removal.
Removing objects
Removing the object once it goes out of bounds is especially useful if you have objects being continually
generated. The ones you remove are replaced by new ones coming in, so you won't end up with an empty
canvas. Also, you won't wind up with too many objects being moved around, which would eventually slow
down the browser.
With many moving objects, you should store their references in an array, and then iterate through the array
to move each one. To remove one of these objects from the array, you use the Array.splice method. To
remove an object, knowing its position and what the boundaries are, you can use something like this for
your if statement:
if (ball.x > canvas.width ||
ball.x < 0 ||
ball.y > canvas.height ||
ball.y < 0) {
balls.splice(balls.indexOf(ball), 1);
}
The || symbol means “OR,” so you're essentially saying: “If the object is off to the right, OR the object is
off to the left, OR it is off to the top OR the bottom, remove it from the array.” This technique is usually fine
for most cases of removal, because it doesn't matter where the object went out of bounds—just that it did.
But in other cases, you might want to respond differently if the object hit a particular boundary, such as the
 
Search WWH ::




Custom Search