Thursday, February 23, 2012

ActionScript 3.0 - How to move an image over the canvas

This will be the first post of a series.
In this post we look at how to move an imported image over the stage.
  1. You'll need an image that will be used to move over the canvas. Could be any image you prefer really. There are plenty to be found on the internet.
  2. Start a new Actionscript 3.0 document in Flash CS5
  3. Import the image into your stage or library. File > Import > Import To Stage or CTRL+R
  4. Right-click the image and convert it to a symbol

A MovieClip will be added to your library and the item is ready to be instantiated using code at runtime.

Let's head over to the actions pane of our stage and write the necessary code to move the icon inside the canvas pressing the arrow keys UP-DOWN-LEFT & RIGHT.

First lines of code :

import flash.display.MovieClip;

//Declare a UserIcon of the type MovieClip
var userIcon:MovieClip;

//Instantiate the MovieClip
userIcon = new UserIcon;

//Add it to the DisplayList.
//On startup the imagelist it's children get added to the stage
stage.addChild(userIcon);

Launch the application. The picture should appear in the left-top corner of the canvas.

Make the image move code :

We need an Eventlistener who will monitor if a keyboard button is pressed.
We need a function who will determine what key is pressed and who acts accordingly.

//First create the Eventlistener which is a KeyboardEvent
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyDown);

//Now we are monitoring keyboard button keydown events but we
//still have to determine what key is pressed and then act accordingly
//We will also need to set the boundary of the stage to make sure the picture
//Doesn't dissapear when we move it out of the canvas boundaries
function keyDown(e: KeyboardEvent):void{

       //Use the keycode of the eventlistener to determine what key got pressed.
       switch(e.keyCode)
       {
             //In case the keyboard button UP is pressed
             case Keyboard.UP:
                    if(userIcon.y > 0)
                           userIcon.y = userIcon.y - 5;
                    break;
             //In case the keyboard button DOWN is pressed
             case Keyboard.DOWN:
                    if(userIcon.y +5 < stage.stageHeight -userIcon.height)
                           userIcon.y = userIcon.y + 5;
                    break;
             //In case the keyboard button LEFT is pressed
             case Keyboard.LEFT:
                    if(userIcon.x > 0)
                           userIcon.x = userIcon.x - 5;
                    break;
             //In case the keyboard button RIGHT is pressed
                    case Keyboard.RIGHT:
                    if(userIcon.x +5 < stage.stageWidth -userIcon.width)
                           userIcon.x = userIcon.x + 5;
                    break;
                    trace(e.keyCode);
       }
}


Next post we'll add more features!