HTML and CSS Reference
In-Depth Information
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);
}());
};
</script>
</body>
</html>
You start out by declaring variables for the ball, the line, gravity, and bounce. Then position the ball and
line, and calculate the cos and sin of the line's rotation. The normal motion code is placed near the top of
the drawFrame function.
Then you get the initial x, y position of the ball in relation to the line, by subtracting the line position from
the ball position.
And now you're ready to rotate something! But, when you look at the next couple of lines of code, you may
notice something that seems wrong:
//rotate coordinates
x2 = x1 * cos + y1 * sin,
y2 = y1 * cos - x1 * sin,
The plus and minus are reversed from the original formula you were given for coordinate rotation, which is:
x1 = x * cos(rotation) - y * sin(rotation);
y1 = y * cos(rotation) + x * sin(rotation);
That's not a mistake, remember, we want to rotate the line so it's a flat surface. If the line is rotated 10
degrees, then using the original formula, you would wind up rotating it 10 degrees more, making it 20
degrees—that's going the wrong way! You actually want to rotate it -10 degrees to put it at 0. You could
have calculated the sine and cosine to be Math.sin(-angle) and Math.cos(-angle) , but eventually,
you'll need the sine and cosine of the original angle, in order to rotate everything back.
Rather than making two cosine and sine variables (at double the cost of calculation), you can use an
alternative form of coordinate rotation to rotate everything in the opposite direction. It's as simple as
reversing the plus and minus, as you just saw. If the line is at 10 degrees rotation, this will rotate
everything -10 degrees, putting it at 0 degrees, or flat. Then do the same to the velocity.
You don't need to actually rotate the line instance, because it's just there for your eyes—to let you see
where the ball is supposed to bounce. It's also a handy place to store the angle and position of the
surface, since you can move and rotate with code.
Then you can perform the bounce. You do this using the x2 , y2 position values and the vx1 , vy1 velocity
values. Because y2 is in relation to the line instance, the “bottom” boundary is the line itself, which will be
0. Taking into account the size of the ball, you check to see whether y2 is greater than 0 - ball.radius ,
which looks like this:
Search WWH ::




Custom Search