The previous post showed an example of create a Sprite object that would animate through BitmapData manipulation. In order for that to work, you’ll need to a ‘controller’ class that handles key input and user interaction. The follow is the code that will turn your sprite into a moving character.
Source code follows:
package {
import Game.Actor;
import flash.display.Sprite;
import flash.events.Event;
import flash.events.KeyboardEvent;
public class BoyWonder extends Sprite
{
private var f:Actor;
public function BoyWonder()
{
stage.stageHeight = 550; // stage is 550 pixels wide
stage.stageWidth = 400; // 400 pixels high
stage.frameRate = 30; // running at 30 frames per secon.
addEventListener(Event.ENTER_FRAME, update); // each frame execute update method.
stage.addEventListener(KeyboardEvent.KEY_DOWN, handleKeyDown); // when key is pressed
stage.addEventListener(KeyboardEvent.KEY_UP, handleKeyUp); // when key is released
f = new Actor(); // I don't know why I called it f : - )
addChild(f);
}
public function update(evt:Event):void {
f.doAction(); // update the actor. This method moves the character and advances the frame.
}
public function handleKeyDown(evt:KeyboardEvent):void { // if keys are pressed, change the direction of the characters.
if (evt.keyCode == 37) {
f.setDir(0);
}
if (evt.keyCode == 38) {
f.setDir(2);
}
if (evt.keyCode == 39) {
f.setDir(1);
}
if (evt.keyCode == 40) {
f.setDir(3);
}
}
public function handleKeyUp(evt:KeyboardEvent):void {
//trace('key-up!'+ evt.keyCode);
}
}
}