HTML and CSS Reference
In-Depth Information
This portion of the chapter gets pretty complex, so we go through the code one concept at a time. The final
document, with all of these concepts incorporated, is 10-real-walk.html .
Giving It Some Space
Because this thing is actually going to be walking around the screen, let's make all the parts a bit smaller
so that there is room for it to move around. Take the original four segments and make them half of what
they were:
var segment0 = new Segment(50, 15),
segment1 = new Segment(50, 10),
segment2 = new Segment(50, 15),
segment3 = new Segment(50, 10);
Next, because it will move around and react with boundaries, define variables for vx and vy :
var vx = 0,
vy = 0;
At this point, if you run the file, you'd have a miniature, working version of the previous example.
Adding Gravity
Now you need to create some gravity; otherwise—even if you add in the boundary detection—the legs are
just going to float in space. The gravity variable is controlled by another slider, so, create a new slider
object, name it gravitySlider , and set its minimum to 0, maximum to 1, and value to 0.2. Here's the
relevant of code that initializes that last slider:
var gravitySlider = new Slider(0, 1, 0.2);
gravitySlider.x = 110;
gravitySlider.y = 10;
gravitySlider.captureMouse(canvas);
You also need to do the velocity calculations, along with the gravity acceleration. Rather than jamming all
this into the drawFrame function, make a call to another function named setVelocity :
(function drawFrame () {
window.requestAnimationFrame(drawFrame, canvas);
context.clearRect(0, 0, canvas.width, canvas.height);
cycle += speedSlider.value;
setVelocity();
walk(segment0, segment1, cycle);
walk(segment2, segment3, cycle + Math.PI);
segment0.draw(context);
segment1.draw(context);
segment2.draw(context);
segment3.draw(context);
speedSlider.draw(context);
 
Search WWH ::




Custom Search