To make something happen, we'll call the following function once for
every frame.
The code is pretty simple -- it adjusts the hero position depending on which keys are down.
The interesting bit is that it first saves a copy of the hero x & y position in a couple of local variables.
var hero_speed = 3; // How fast the hero goes
function handle_keys_that_are_pressed() {
var prev_x = hero.x;
var prev_y = hero.y;
if (keys[37]) { // Left
hero.x -= hero_speed;
}
if (keys[39]) { // Right
hero.x += hero_speed;
}
if (keys[38]) { // Up
hero.y -= hero_speed;
}
if (keys[40]) { // Down
hero.y += hero_speed;
}
}
if (hero.x == prev_x && hero.y == prev_y) hero.animation_rate= 0 // not moving
else hero.animation_rate= 2; // wriggling legs
}
After the adjustments (if any) have been made, we can check to see if the hero actually moved.
If it didn't move, we set the animation rate to zero (stopped). Otherwise we set it to 2, which provides a pleasing amount of wriggle.