Moving Objects with the Keys using AS

Step 1.
Start off by making a new Flash document. For this tutorial I’ve made one with dimensions of 250×190. The image that i’ve used can be saved from image a) and then imported into Flash (File > Import > Import to Stage). Once it’s on the stage, left click on it and then convert it to a MC (Movie Clip) by going to Insert > New Symbol and then choosing Movie Clip & OK. In the Timeline name the frame, that the MC is on, “images” and create a new layer below it called”Script”.

Step 2.
Click on the MC on the stage and open up the properties panel. Below the “Movie Clip” drop down enter “square”. When we write the Action Script we will be referencing the MC by “square”.

Step 3.
Next, click on the 1st frame of “script” and layer open up the “Actions Panel”. Type in the code shown below. “var speed 5″ is the variable which, as you’ve proabably guessed, will store the value for speed! 🙂 This will mean that it will move 5 pixels with a single press of a key. You can change it to whatever you like.” this.onEnterFrame = function(){ } “is a function which will repeatedly run any script we put in between the braces {}, at the frame rate of the SWF file.

Step 4.
To move “square” we need to repeatedly check to see if any of the arrow keys are being pressed. To do this we add the IF statement “if(key.isDown(Key.UP)){}”. This will check if the UP key is pressed down.

Step 5.
Next, inbetween the {} of the IF statment we enter what we want to happen when the Up key is pressed. The code square._y -= speed; will reduce the Y co-ordinate of “square” by the speed (5), everytime the UP key is pressed.

Step 6.
Next we need to add the code to mave “square” down, left and right. For the down movement, instead of deducting the speed, we want to add the speed value to the Y co-ordianted, so we put +=speed. Now with this in mind, you add the code for the left and right movement, as shown below!