HTML and CSS Reference
In-Depth Information
ball . x
ball . x
+ ball . width / 2
Figure 6-3. This ball is just slightly off the canvas, but it needs to bounce.
After you determine that the object has crossed at least a bit of one of the boundaries, you now reverse
the velocity on that axis. But there's a little more to it than that. You must reposition the object so that it sits
on the edge of the boundary. This has the obvious visual effect of making the object look more like it's
hitting and bouncing, rather than sinking into the wall. But it is also a necessary step for other reasons.
You find that if you don't adjust the object's position, then on the next frame, it might still be past that
boundary, even after it moves. If this happens, the object will again reverse its velocity and head back into
the wall! Then you get a situation where the object seems to be stuck halfway in and out of the wall, just
sitting there and vibrating—it's not pretty.
The point where you need to place the object to have it sitting on the boundary is actually the same point
you are checking in the if statement. You just need to restate it with a little basic algebra. Here's the full
if statement for the x axis:
if (ball.x + ball.radius > right) {
ball.x = right - ball.radius;
vx *= -1;
} else if (ball.x - ball.radius < left) {
ball.x = left + ball.radius;
vx *= -1;
}
Figure 6-4 shows what the ball looks like after being repositioned.
right
right
-ball.width/ 2
Figure 6-4. The ball has been repositioned to be exactly against the boundary.
The steps for bouncing are as follows:
C k w t r t e j t w t t y .
 
 
Search WWH ::




Custom Search