HTML and CSS Reference
In-Depth Information
<script src="utils.js"></script>
<script src="ball.js"></script>
<script>
window.onload = function () {
var canvas = document.getElementById('canvas'),
context = canvas.getContext('2d'),
ball = new Ball(),
vx = 1,
vy = 1;
ball.x = 50;
ball.y = 100;
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
ball.x += vx;
ball.y += vy;
ball.draw(context);
}());
};
</script>
</body>
</html>
Again, play around with the velocity variables until you get a good feel for them. Don't forget to try out
some negative values.
Angular velocity
So far, so good. You have some real animation going on, using velocity on two axes. But in many cases—
maybe most cases—x and y velocity won't be the initial data you have.
We are kind of cheating with the definition of velocity here. We said it's speed in a direction, but now you
have two different speeds in two different directions. On the canvas, you position objects by placing them
on x, y coordinates. So you need to end up with a velocity and position on both axes, but that's not
necessarily how you start.
What if you have a value for speed and an angle for direction, per the definition. Say you want something
to move at an angle of 45 degrees and a speed of 1 pixel per frame. There isn't any vx or vy , or anything
even similar in that description.
Fortunately, you've already been introduced to the tools you need to derive vx and vy from that
description. Think back to the discussion of trigonometry in Chapter 3. Now, look at Figure 5-4, which
shows what you want the ball to do on each frame: Move 1 pixel at an angle of 45 degrees.
 
Search WWH ::




Custom Search