HTML and CSS Reference
In-Depth Information
This function has three parameters: two segments ( segA and segB ) and cyc , which stands for cycle . The
rest of the code is what you've been using. Now, to make segment0 and segment1 walk, just call it like
this:
walk(segment0, segment1, cycle);
And now you're ready to make segment2 and segment3 walk as well. This is what your drawFrame
function ends up as:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
cycle += 0.02;
walk(segment0, segment1, cycle);
walk(segment2, segment3, cycle);
segment0.draw(context);
segment1.draw(context);
segment2.draw(context);
segment3.draw(context);
}());
But if you try that, you're not going to see the second leg. The problem is that both legs are moving exactly
in sync, so they appear as one. Once again, you need to desynchronize. Last time, you offset the bottom
segment's position on the cycle from the top segment's position. This time, you offset the second leg from
the first. Again, this comes down to changing the value it's using for cycle . And once again, rather than
keeping track of two different variables, just add something to or subtract something from cycle before
you send it into the walk method. So, the drawFrame function becomes the following:
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
cycle += 0.02;
walk(segment0, segment1, cycle);
walk(segment2, segment3, cycle + Math.PI);
segment0.draw(context);
segment1.draw(context);
segment2.draw(context);
segment3.draw(context);
}());
We use Math.PI to put the second leg 180 degrees out of sync with the first, so the first leg moves
forward while the second is moving back, and vice versa. You can try it out with some different values, say
Math.PI/2 , and see that it looks a lot more like a gallop than a walk or run—which you might need to use
someday!
The file is available as 08-walking-4.html and looks like Figure 13-5. The base segments (the “thighs”)
have been made a bit larger than the lower segments (the “calves”). And because of the dynamic way
everything is set up, it all works no matter what the sizes are. In the next version, you make more things
 
Search WWH ::




Custom Search