spriteDirection = 0;
this.onEnterFrame = function() {
if (Key.isDown(Key.RIGHT)) {
setDirection(0);
_root.sprite._x += 3;
}
if (Key.isDown(Key.LEFT)) {
setDirection(1);
_root.sprite._x -= 3;
}
if (Key.isDown(Key.DOWN)) {
_root.sprite._y += 3;
}
if (Key.isDown(Key.UP)) {
_root.sprite._y -= 3;
}
};
function setDirection(param){
if(param==0){
sprite._xscale = 100
} else {
sprite._xscale = -100
}
}
|
Method 1
You will notice that the code is very simple.
We are using onEnterFrame to check at regular interval which key is pressed.
Then we use the property isDown of the Key object to check when a key is pressed.
When we detect that a key is pressed we check if it is the right arrow, the left arrow, the top arrow or the bottom arrow by checking the 4 respective properties RIGHT, LEFT, TOP, BOTTOM of the key object.
if we detect that the right key or the left key is pressed we turn the sprite in the correct direction by calling the setDirection function. depending on the value (0 for right and 1 for left) we set the _xscale property for the sprite to -100 or 100.
|