AS3 example Keyboard control

The educational technology and digital learning wiki
Revision as of 20:37, 4 November 2007 by Widged (talk | contribs)
Jump to navigation Jump to search

Draft

<pageby nominor="false" comments="false"/>

ActionScript Program

package {
  import flash.display.Sprite;
  import flash.display.Stage;
  import flash.events.Event;
  import flash.events.KeyboardEvent;
  import flash.ui.Keyboard;

  public class KeyboardDemo extends Sprite { 
    private var player:Sprite;

    public function KeyboardDemo() {

      player = createAvatar(0xFFFF00) // size, color yellow
      player.x = 200;
      player.y = 100;
      addChild(player);

      stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);

    }

    private function keyPressedDown(event:KeyboardEvent):void {
      var key:uint = event.keyCode;
      var step:uint = 5
      switch (key) {
          case Keyboard.LEFT :
            player.x -= step;
            break;
          case Keyboard.RIGHT :
            player.x += step;
            break;
          case Keyboard.UP :
            player.y -= step;
            break;
          case Keyboard.DOWN :
            player.y += step;
            break;
      }
    }

    private function createAvatar(bgColor:uint):Sprite {
      var s:Sprite = new Sprite();
      s.graphics.beginFill(bgColor);
      s.graphics.drawCircle(0, 0, 40);
      s.graphics.endFill();
      s.graphics.beginFill(0x000000);
      s.graphics.drawCircle(-15, -10, 5);
      s.graphics.drawCircle(+15, -10, 5);
      s.graphics.endFill();
      s.graphics.lineStyle(2, 0x000000, 100);
      s.graphics.moveTo(-20,15);
        //this will define the start point of the curve
      s.graphics.curveTo(0,35, 20,15); 
        //the first two numbers are your control point for the curve
        //the last two are the end point of the curve
      return s;
    }
  }
}

Walkthrough

---

package {
  import flash.display.Sprite;
  import flash.display.Stage;
  import flash.events.Event;
  import flash.events.KeyboardEvent;
  import flash.ui.Keyboard;

  public class KeyboardDemo extends Sprite { 

package declaration, import statements, class definition.

---

    private var player:Sprite;

we define the sprite that will be moved around the screen. It needs to be declared before the constructor because the variable will be used in different functions.

---

    public function KeyboardDemo() {

      player = createAvatar(0xFFFF00) // size, color yellow
      player.x = 200;
      player.y = 100;
      addChild(player);

      stage.addEventListener(KeyboardEvent.KEY_DOWN, keyPressedDown);

    }

Constructor function. The novelty here is the use of stage. This time, we will listen to events that take place anywhere on the stage rather than a given sprite.

Because we refer to the stage variable, to know what the variable corresponds, we need to import the Stage class. Make sure import flash.display.Stage; is listed among the import statements.

---

    private function keyPressedDown(event:KeyboardEvent):void {
      var key:uint = event.keyCode;
      var step:uint = 5
      switch (key) {
          case Keyboard.LEFT :
            player.x -= step;
            break;
          case Keyboard.RIGHT :
            player.x += step;
            break;
          case Keyboard.UP :
            player.y -= step;
            break;
          case Keyboard.DOWN :
            player.y += step;
            break;
      }
    }

This function defines what happens when a keydown event takes place on the stage. Any key down event would trigger that function. This could be pressing on a "a", pressing on a "shift key". Any key pressed will cause this function to execute. We need therefore to write some code that will trigger visible actions only when arrow keys (left, up, right, down) are pressed.

If you have used different computers, at home vs at the lab, desktop vs laptop computer, PC vs Mac, you know that the keyboard can be layed out differently in these different environments. A numeric code is used to provide a unique identifier across environments. Because us, humans, are not very good at remembering a large number of numeric codes, flash kindly provides us with a Keyboard class that has for main function to provide us with easy to read Keyboard information (Keyboard.LEFT, Keyboard.UP, Keyboard.RIGHT, Keyboard.DOWN).

The left, up, right, down variable *must* be written in uppercase because Flash is case sensitive (right, Right, and RIGHT are tree different varibles). They are in uppercase because the convention is to write this way program constants, that is values that don't get to be modified at any point of the program.

We define a step variable for ease of maintenance. For a second, let's imagine we had used player.x -= 5;. If we were to change our mind and change the distance to move by to 40 pixels rather than 5, we would have to change the value in 4 different places. The slightest distraction and we may forget to update all four values, meaning that we will need to compile a first time, identify the error, edit the program file to correct it, re-compile, re-test. It is far less troublesome to create a variable to hold the step value and use that variable when it comes to updating the x and y values of the player.

---

    private function createAvatar(bgColor:uint):Sprite {
      var s:Sprite = new Sprite();
      s.graphics.beginFill(bgColor);
      s.graphics.drawCircle(0, 0, 40);
      s.graphics.endFill();
      s.graphics.beginFill(0x000000);
      s.graphics.drawCircle(-15, -10, 5);
      s.graphics.drawCircle(+15, -10, 5);
      s.graphics.endFill();
      s.graphics.lineStyle(2, 0x000000, 100);
      s.graphics.moveTo(-20,15);
        //this will define the start point of the curve
      s.graphics.curveTo(0,35, 20,15); 
        //the first two numbers are your control point for the curve
        //the last two are the end point of the curve
      return s;
    }

We have been playing with graphics a lot, already. This creates a smiley face. A yellow circle in the background, two small black circles for the eyes, a curve for the smile.

---

  }
}

closing the class definition and then the package declaration. ---

Variants

  • Adding a jump option triggered by the space letter key.
  • Using letter keys for navigation.

Challenge

Design some dancing mat game type of game. Instructions on the sequence to repeat are given as a sequence of characters "U L R D U U D". There is a starting point and an end point. If the player followed the sequence exactly, he should arrive at the end point.