gavin sim logo
 

Week 1

Week 2

Week 3

Week 4

Week 5

Week 6

Week 7

Week 8

Week 9

Teaching > ActionScript

Switch Statements

You are going to create a simple example of a box moving around the stage.

Create a new flash document. Draw a small rectangle on the stage, convert it to a movieclip and give it an instance name of box.

Create a new layer and name it actions.

Open the actions panel and type the following:

stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyPressed);

function onKeyPressed(evt:KeyboardEvent):void{
  switch(evt.keyCode){
     case Keyboard.UP:
     box.y-=5;
     break;
     case Keyboard.DOWN:
     box.y+=5;
     break;
     case Keyboard.LEFT:
     box.x-=5;
     break;
     case Keyboard.RIGHT:
     box.x+=5;
     break;
     default:
     trace("keyCode:", evt.keyCode);
  }
}

The first line starts by adding a listener to the stage for the keyBoardEvent.When the event is heard, the listener will call the onKeyPressed() function.

The onKeyPressed() function is defined and the keyboardEvent is passed to the function sending the keyCode to the function that is stored in evt argument. The keyCode is a unique number assigned to every key and is useful to identify which key has been pressed. Instead of using an if statement in this case we have used a switch. the case is just simply determining if the value after it is true, if it is then the code will execute and then the break terminates the switch statement. The default is optional but is sometimes useful for error handling.

 

Excercise

Change the code so a variable is used to alter the distance the box moves when a key is pressed, thus removing the 5.