HTML and CSS Reference
In-Depth Information
vx += ax;
vy += ay;
vy += gravity;
vx *= friction;
vy *= friction;
ball.x += vx;
ball.y += vy;
ball.draw(context);
Don't worry about what it all means, just know that we need to run this code over and over to generate
each new frame.
So, how do these loops run? Here's a misguided attempt, which reflects an error that many beginning
programmers make. It's based on the while loop structure that exists in almost every programming
language. You set up a loop to run indefinitely, updating the ball from within:
while (true) {
ball.x += 1;
}
It seems simple: The while evaluation always passes because we're testing a value of true , so the loop
keeps executing. We increment the ball's x position by 1 each time through the loop, from 0 to 1 to 2, 3, 4,
etc. Each time it moves across the canvas from left to right.
If you've made the same mistake, you know that the ball doesn't move across the canvas, and in fact you
won't see it at all—it's already moved past the right side of the screen. Why doesn't it move to all the
points in between? Actually, it did! But you didn't see it because the canvas element was never updated.
Figure 2-5 is another flowchart that shows essentially what happens.
Figure 2-5. Why you can't animate with a while loop
You applied the rules and moved the ball into position, creating a new scene, but it never got displayed
because you didn't draw the object to the canvas at the end of a frame. This is an important point.
Here is the sequence of actions you must take on each frame to animate:
1.
Execute all the code that needs to be called for that frame.
2.
Draw all objects to the canvas element.
3.
Restart the process to render the next frame.
 
Search WWH ::




Custom Search