HTML and CSS Reference
In-Depth Information
Now comes the first interesting part: the collision detection. You want to know whether the bottom of the
segment in question has gone below the bottom boundary. In this example, that's specified by
canvas.height
.
Probably the easiest way to do this is by performing a rough calculation of our segment bottom by getting
the y position of its pin, and adding on the extra space of the segment end. Then check whether it is
greater than the height of the canvas. It's not the most precise measurement, but it serves the purposes of
this example, so that's how you start the
checkFloor
function:
function checkFloor (seg) {
var yMax = seg.getPin().y + (seg.height / 2);
if (yMax > canvas.height) {
//do reaction...
}
}
If you've determined that
yMax
is greater than the
canvas.height
(or, if the leg has hit the floor), what do
you do? Just as in other boundary collisions, you first want to move the object so it's touching the
boundary. If
yMax
is the lowest edge of the segment and
canvas.height
is the floor, you need to move
the segment back up exactly the distance between them. In other words, say
canvas.height
is 400 and
yMax
is 420. You need to change the segment's y position by -20, but you don't want to move
only
the
segment. You want to move
all
the segments by that amount, because they are all part of the same body
and must move as one. So, you get something like this:
function checkFloor (seg) {
var yMax = seg.getPin().y + (seg.height / 2);
if (yMax > canvas.height) {
var dy = yMax - canvas.height;
segment0.y -= dy;
segment1.y -= dy;
segment2.y -= dy;
segment3.y -= dy;
}
}
This iteration of the example is worth playing with some more. Adjust the slider values to see the different
walk cycles in action. You get more of a feel for them with the legs interacting with the environment. Of
course, it's still not really walking yet—that's up next.
Handling the Reaction
The legs are successfully colliding with the floor, but other than repositioning themselves, there's no real
reaction. The whole reason you walk is to get some horizontal motion going—x velocity, in this case.
Furthermore, your walk cycle should give you a bit of y velocity as well, at least enough to briefly
counteract gravity. You see this more in a fast run, where you might get slightly airborne during a cycle.
One way of looking at this is that your foot is moving down. When it hits the floor, it can't move down any
more, so that vertical momentum goes back up to your body, moving it up. The stronger your foot is