HTML and CSS Reference
In-Depth Information
if (y2 > -ball.radius) {
//rotate coordinates
var x2 = x1 * cos + y1 * sin,
//rotate velocity
vx1 = ball.vx * cos + ball.vy * sin,
vy1 = ball.vy * cos - ball.vx * sin;
y2 = -ball.radius;
vy1 *= bounce;
//rotate everything back
x1 = x2 * cos - y2 * sin;
y1 = y2 * cos + x2 * sin;
ball.vx = vx1 * cos - vy1 * sin;
ball.vy = vy1 * cos + vx1 * sin;
ball.x = line.x + x1;
ball.y = line.y + y1;
}
ball.draw(context);
line.draw(context);
}());
All the code in bold has been moved from outside the if statement to inside the statement, so it will
execute only if a hit actually occurs, rather than every single frame. This has saved quite a number of
calculations. As your animations get more complex, it becomes important to think about things like this.
Making it dynamic
You can now start to make the action a little more dynamic. Using the previous example, let's adjust the
angle of the line in real time using the mouse. Like prior examples, add our mouse tracking utility function
to the top of the script:
var mouse = utils.captureMouse(canvas);
We'll use the mouse location to affect the line's rotation angle. Inside the drawFrame function, after the
normal motion code, move the assignment for line.rotation and the calculations for cos and sin , since
we'll need these for each frame:
line.rotation = ((canvas.width / 2 - mouse.x) * 0.1) * Math.PI / 180;
var cos = Math.cos(line.rotation),
sin = Math.sin(line.rotation);
Now you can move your mouse back and forth, and the line will tilt one way or the other. The ball should
constantly adjust itself accordingly. Remember that we are converting our degrees to radians here before
drawing the line to the canvas. You can find this exercise implemented in document 06-angle-bounce-
rotate.html .
 
Search WWH ::




Custom Search