HTML and CSS Reference
In-Depth Information
var bounds = ball.getBounds();
console.log(bounds.x);
console.log(bounds.y);
console.log(bounds.width);
console.log(bounds.height);
This prints the ball's bounding box from the viewpoint of the canvas element. Remember that the ball is
drawn from its origin point in the center. The left and top bounds are the ball's radius subtracted from its
position, while the right and bottom bounds are the radius added to its position.
But back to our problem of the ball not falling off the edge of the line. You can call getBounds on the line,
and determine its left and right boundaries from the returned rectangle. If the ball's bounding box is less
than bounds.x (left edge), or if it is greater than bounds.x + bounds.width (right edge), it has gone past
the end of the line segment. We'll put this test in the if statement after the normal motion code:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var bounds = line.getBounds();
//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 (ball.x + ball.radius > bounds.x && ball.x - ball.radius < bounds.x + bounds.width) {
//all the rest of the code that was in this function
}
ball.draw(context);
line.draw(context);
}());
You can see these changes implemented in the file 08-angle-bounce-bounds.html .
Fixing the “under the line” problem
When detecting these collisions, you're first finding out if the ball is in the vicinity of the line, and then
performing coordinate rotation to get the adjusted positions and velocities. At that point, you check if the y2
rotated y position of the ball is past the line, and if so, perform a bounce.
But what if the ball passes under the line? Say the line is in the middle of the canvas, and the ball is
bouncing around on the “floor.” If either the hit test or the bounds check comes back true , our program
will react as the ball has just bounced on the line, and will transport the ball from below the line to above it.
A solution to this is to compare vy1 with y2 , and bounce only if vy1 is greater. Take a look at the diagram
in Figure 10-8.
 
Search WWH ::




Custom Search