HTML and CSS Reference
In-Depth Information
Fixing the “not falling off the edge” problem
You've probably noticed that the ball will continue to roll along the angle of the line, even if it has gone past
the edge of it. This may look strange, but remember that the ball is not actually interacting with the line
object at all—it's all done mathematically. But the results are so exact, it's easy to forget that nothing is
actually “hitting” anything. Since the ball doesn't “know” anything about the line object, it doesn't know
where it starts or ends. But you can tell it where the line is—using either a simple hit test or a more precise
bounds check.
Hit testing
The easiest way to find the line's location is to wrap everything but the basic motion code inside a hit test.
We'll use the utils.intersects function from Chapter 9—and added to our utils.js file—to determine
if the ball's bounding box and the line's bounding box overlap (example 07-angle-bounce-hit-
test.html ):
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
//rotate line with mouse
line.rotation = ((canvas.width / 2 - mouse.x) * 0.1) * Math.PI / 180;
//normal motion code
ball.vy += gravity;
ball.x += ball.vx;
ball.y += ball.vy;
if (utils.intersects(ball.getBounds(), line.getBounds())) {
//all the rest of the code that was in this function
}
ball.draw(context);
line.draw(context);
}());
You can see that for the ball to fall off the edge, its entire bounding box must clear the line. While that
might suffice for some implementations, there's another way to do it that's a little more exact. But naturally,
that means it's a little more complex.
Bounds checking
The getBounds method we defined on the Line and Ball classes returns an object representing a
rectangle, with the properties x , y , width , and height . The reference position of the bounding box is the
global space, meaning the absolute position as drawn to canvas element, with the top-left point being 0, 0.
This is opposed to the relative position of one object to another, though we can calculate this by
subtracting one object's global position from the other.
Let's try it out. Create an instance of the Ball class and then run the following code:
 
Search WWH ::




Custom Search