HTML and CSS Reference
In-Depth Information
}
function move (ball) {
var x1 = ball.x - centerX,
y1 = ball.y - centerY,
x2 = x1 * cos - y1 * sin,
y2 = y1 * cos + x1 * sin;
ball.x = centerX + x2;
ball.y = centerY + y2;
}
function draw (ball) {
ball.draw(context);
}
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
var angle = (mouse.x - centerX) * 0.0005;
cos = Math.cos(angle);
sin = Math.sin(angle);
balls.forEach(move);
balls.forEach(draw);
}());
};
</script>
</body>
</html>
You'll revisit this formula when you get to the discussion of 3D in Chapter 15. In fact, you'll be using it twice
within the same function, to rotate things around two axes and three dimensions. But don't get scared off
yet, there is still a lot to do before you get there.
Bouncing off an angle
We've already bounced off walls, but in real situations, surfaces are not always horizontal or vertical—
sometimes they're angled. This is not the most straightforward equation, but if we break it down to a few
steps you can see how simple the concept is. All we need to do is rotate the whole system so the surface
is flat, do the bounce, then rotate it all back. This means rotating the surface, rotating the coordinates of
the object in question, and rotating the object's velocity vector.
Rotating velocity may sound complex, but you've been storing velocity in vx and vy variables. The vx and
vy define a vector, which is an angle and a magnitude, or length. If you know the angle, you can rotate it
directly. But if you just know the vx and vy , you can apply the advanced coordinate rotation formula to it
and get the same result, just as you did for the position of the ball.
In Figure 10-4, you see the angled surface, the ball, which has hit the surface, and the vector arrow
representing the ball's direction.
 
Search WWH ::




Custom Search