HTML and CSS Reference
In-Depth Information
} else if (ship.y < top - ship.height / 2) {
ship.y = bottom + ship.height / 2;
}
ship.draw(context);
}());
};
</script>
</body>
</html>
This uses the Ship class from Chapter 5, so make sure you include that script in your document. As you
can see, this updated script adds the boundary definitions and the checks for them. We're back to using
separate if and else statements, because the actions are different for each circumstance.
Bouncing
And now we arrive at perhaps the most common, and possibly the most complex of bounds handling
methods. But not to worry—it's not much more complicated than screen wrapping.
The strategy with bouncing is to detect when the object has gone off screen. Only this time, leave it where
it is and only change its velocity. The rules are simple: If the object went off the left or right edge, reverse
its x velocity. If it went off the top or bottom, reverse its y velocity. Reversing an axis velocity is simple:
Multiply the value by -1. If the velocity is 5, it becomes -5; if it's -13, it becomes 13. The code is even
simpler:
vx *= -1;
vy *= -1;
There are a few more differences from screen wrapping. First, in wrapping, you let the object move
completely off the canvas before you reposition it. You do that by taking its position and adding or
subtracting half its width. For bouncing, you want to do almost exactly the opposite. Don't wait until the
object is entirely off the canvas before you make it bounce. In fact, you don't want it to be even partially out
of the picture. If you throw a real ball against a real wall, you wouldn't expect to see it go partially into the
wall before bouncing back. It would hit the wall, stop right there, and then bounce back. The first thing you
want to know is the instant that any part of the object has gone over the edge. All you need to do is
reverse the way you add the half width/height (see Figure 6-3). So, for example, instead of saying this:
if (ball.x - ball.radius > right) ...
you say this:
if (ball.x + ball.radius > right) ...
 
Search WWH ::




Custom Search