document.addEventListener('keydown',function(event) {
varcode = event.keyCode;
if(code == 37) { // left
marker.position.x = marker.position.x-5;
❶ is_moving_left = true;
}
if(code == 38) { // up
marker.position.z = marker.position.z-5;
❷ is_moving_forward = true;
}
if(code == 39) { // right
marker.position.x = marker.position.x+5;
❸ is_moving_right = true;
}
if(code == 40) { // down
marker.position.z = marker.position.z+5;
❹ is_moving_back = true;
}
if(code == 67) is_cartwheeling = !is_cartwheeling;// C
if(code == 70) is_flipping = !is_flipping; // F
});
❶The avatar is moving left.
❷The avatar is moving forward.
❸The avatar is moving right.
❹The avatar is moving backward.
This turns the movement controls on, but we still need to be able to turn
them off. Since we used keydown to decide when a key is being pressed, you
can probably guess how we’ll decide when a key is let go.
After the last line of the keydown event-listener code—after the }); line—add
the following keyup event-listener code.
document.addEventListener('keyup',function(event) {
varcode = event.keyCode;
if(code == 37) is_moving_left = false;
if(code == 38) is_moving_forward = false;
if(code == 39) is_moving_right = false;
if(code == 40) is_moving_back = false;
});
With that, we should be able to move our avatar with the arrow keys and see
the avatar’s hands and feet swing back and forth. When we let go of those
keys, the avatar’s walking should stop.
Cool!
report erratum • discuss
Walking When Moving • 65
Prepared exclusively for Michael Powell