Home | Contact Us | Store

Use Keyboard to Move Object with ActionScript 3 (2)

In the first Flash ActionScript 3 tutorial, the ball moved only when users pressed on the keys. In this tutorial, we also Keyboard keys to move the ball around on the stage of Flash Movie. However the ball will keep on moving when the user press on a key until another key is pressed.
Your flash player version is too old to see this video file!

Flash Tutorial Content:

In previous Flash ActionScript tutorial, the ball will move only when we pressed down the arrow keys. The ball will stop moving when we release the keys. In this Flash ActionScript tutorial, we allow the ball keep on moving on the stage of Flash Movie even when we release the arrow keys. The ball will keep on moving until we press another arrow key.

Please use the Mouse to click on the above Flash Movie and start playing to see how it works.

Flash ActionScript Codes:

// We need Keybpard control
import flash.events.KeyboardEvent;

//declare variable to use later
var direction:String;

// Obtain which keys are pressed and translate to direction.
function detectKey(event:KeyboardEvent):String {

if (event.keyCode == 39) {
direction = "right";
} else if (event.keyCode == 37) {
direction = "left";
} else if (event.keyCode == 38) {
direction = "up";
} else if (event.keyCode == 40) {
direction = "down";
} else if (event.keyCode == 32) {
direction = "stop";
}

return direction;

}

 

function moveBall(evt:Event) {

switch (direction) {case 'up' :
football_mc.y -= 2;
break;

case 'down' :
football_mc.y += 2;
break;

case 'right' :
football_mc.x += 2;
break;

case 'left' :
football_mc.x -= 2;
break;

case 'stop' :
// no action is required
break;

}

output_txt.text = "Location of ball: " + Math.round(football_mc.x) + "," + Math.round(football_mc.y);

}


// Hook up the Keyboard event with detectKey function
stage.addEventListener(KeyboardEvent.KEY_DOWN, detectKey);

// send movement to ball upon receive key press
stage.addEventListener(Event.ENTER_FRAME, moveBall);

Download Flash Source File:

Flash Source File keyboard-2.fla

Remarks:

Instead of using the arrow keys, you can also use other keys to move objects on the stage. You don't need to remember the keyCodes of keys on the Keyboard. You can check the keyCodes by using ActionScript 3. Please check next Flash ActionScript tutorial.

Keyboard Control ActionScript Tutorial