Wednesday, March 19, 2008

Key object: Creating keyboard controls



The Key object is a collection of ActionScript elements that handle keypress detection. Using the methods of the Key object, you can retrieve the last key pressed, or test whether a particular key has been pressed. The Key object is commonly used to create keyboard controls for Flash movies. The properties of the Key object are constants representing the keys most commonly used to control games.


KEY.LEFT
Property; constant associated with the key code value for the Left Arrow key
KEY.RIGHT
Property; constant associated with the key code value for the Right Arrow key
KEY.UP
Property; constant associated with the key code value for the UP Arrow key
KEY.DOWN
Property; constant associated with the key code value for the Down Arrow key

I imported an airplane gif to the stage, convert it to movie clip, give instance name "player" and typed this code in the ActionScript Panel:

var speed = 20

this.onEnterFrame = function () {

//move player to go down
if (Key.isDown(Key.DOWN))
{
player._y +=speed
}

//move the player to go up
else if (Key.isDown(Key.UP))
{
player._y -=speed
}

//move player to the left
else if (Key.isDown(Key.LEFT))
{
player._x -=speed
}

//move player to the right
else if (Key.isDown(Key.RIGHT))
{
player._x +=speed
}
}

player - is the instance name given to the airplane gif
player._x - the "x" refers to the horizontal axis
player._y - the "y" refers to the vertical axis

I used the "else if" statement so the plane will move one direction at a time.


No comments: