HTML and CSS Reference
In-Depth Information
You now have a new position and velocity for the ball. Next, rotate everything back to the original angle, as
shown in Figure 10-7.
Ball
Velocity
after bounce
Surface
Figure 10-7. After rotating back
You've just detected the collision, adjusted the position, and changed the velocity, all on an angled
surface. That's the theory behind it anyway, let's move on to some real code.
Performing the rotation
Before we get started, we're going to need something to act as an angled surface. This is more for your
eyes than for any mathematical necessity. For bouncing off of flat surfaces, you can use the boundaries of
the canvas. But for an angled surface, it will help to draw a line at an angle, so you can see the ball
bouncing on it.
For this, we're going to create a new Line class that we can position and draw a horizontal line using the
canvas drawing API. It also contains a fairly comprehensive getBounds method that will allow us to
perform collision detection with it—even when rotated—so we can create an angled surface. Place this
class in the file line.js which we'll import into our examples:
function Line (x1, y1, x2, y2) {
this.x = 0;
this.y = 0;
this.x1 = (x1 === undefined) ? 0 : x1;
this.y1 = (y1 === undefined) ? 0 : y1;
this.x2 = (x2 === undefined) ? 0 : x2;
this.y2 = (y2 === undefined) ? 0 : y2;
this.rotation = 0;
this.scaleX = 1;
this.scaleY = 1;
this.lineWidth = 1;
}
Line.prototype.draw = function (context) {
context.save();
 
Search WWH ::




Custom Search