The Script if(Key.isDown(Key.UP)){ // execute script }
How Does it Work? We call isDown (function) and we pass it the value of the key which we want to know is being pressed or not. It will return a boolean value, true if the key is being pressed, or false if it is not. We know that an if statement will execute if the value in the '()' is true, so we don't have to type: if(Key.isDown(Key.UP) == true)
So How Do I Make Stuff Move?! Why, by simple using a script similar to this: (note: this should be in a movieclip or an enterFrame event)
The first if tests the up key, the second tests down, the third right, fourth left. The this.(_x/_y) (+/-) = 5 adjusts the objects X and Y coordinates moving it around the stage.
If you want to use different keys on the keyboard, you can refer to this chart and use the numbers in place of the Key.* .
var leftDown:Boolean = false; var upDown:Boolean = false; var rightDown:Boolean = false; var downDown:Boolean = false; //how fast the character will be able to go var mainSpeed:int = 5; //adding a listener to mcMain that will move the character mcMain.addEventListener(Event.ENTER_FRAME, moveChar); function moveChar(event:Event):void{ //checking if the key booleans are true then moving //the character based on the keys if(leftDown){ mcMain.x -= mainSpeed; } if(upDown){ mcMain.y -= mainSpeed; } if(rightDown){ mcMain.x += mainSpeed; } if(downDown){ mcMain.y += mainSpeed; } //keeping the main character within bounds if(mcMain.x <= 0){ mcMain.x += mainSpeed; } if(mcMain.y <= 0){ mcMain.y += mainSpeed; } if(mcMain.x >= stage.stageWidth - mcMain.width){ mcMain.x -= mainSpeed; } if(mcMain.y >= stage.stageHeight - mcMain.height){ mcMain.y -= mainSpeed; } } //this listener will listen for down keystrokes stage.addEventListener(KeyboardEvent.KEY_DOWN, checkKeysDown); function checkKeysDown(event:KeyboardEvent):void{ //making the booleans true based on the keycode //WASD Keys or arrow keys if(event.keyCode == 37 || event.keyCode == 65){ leftDown = true; } if(event.keyCode == 38 || event.keyCode == 87){ upDown = true; } if(event.keyCode == 39 || event.keyCode == 68){ rightDown = true; } if(event.keyCode == 40 || event.keyCode == 83){ downDown = true; } } //this listener will listen for keys being released stage.addEventListener(KeyboardEvent.KEY_UP, checkKeysUp); function checkKeysUp(event:KeyboardEvent):void{ //making the booleans false based on the keycode if(event.keyCode == 37 || event.keyCode == 65){ leftDown = false; } if(event.keyCode == 38 || event.keyCode == 87){ upDown = false; } if(event.keyCode == 39 || event.keyCode == 68){ rightDown = false; } if(event.keyCode == 40 || event.keyCode == 83){ downDown = false; }