Kirupa Forum , Diagonal movement sample
Use Arrow Keys, ASWD and Q,E to interact
Sample showing how list can help, when you need multiple keys pressed at same time.
You can use too, a list with function references, its just a sample.
package {
import flash.text.TextField;
import flash.utils.Dictionary;
import flash.events.KeyboardEvent;
import flash.events.Event;
import flash.display.Shape;
import flash.display.Sprite;
public class FlashTest extends Sprite {
private var circle:Shape = new Shape();
private var dic:Dictionary = new Dictionary();
private var list:Array = [];
public function FlashTest() {
// write as3 code here..
addChild(drawShape(circle, 0xff0000, 10));
circle.x = circle.y = 300;
//stage.frameRate = 10;
stage.addEventListener(KeyboardEvent.KEY_DOWN, keyboard);
stage.addEventListener(KeyboardEvent.KEY_UP, keyboard);
stage.addEventListener(Event.ENTER_FRAME, animate);
initDic();
}
private function animate (e:Event):void{
if(!list.length) return;
var n:uint;
var a:Array;
for each (n in list){
a = dic[n];
circle[a[0]] += a[1];
}
}
private function initDic():void{
// << 37 /\ 38 >> 39 \/ 40
// a 65, w 87, d 68, s 83, q 81, e 69,
//left key
dic[37] = ["x",-3];
//up
dic[38] = ["y",-3]
//right
dic[39] = ["x",3];
//down
dic[40] = ["y",3];
// more heigth
dic[87] = ["scaleY", 0.3];
dic[83] = ["scaleY", -0.3];
//width
dic[65] = ["scaleX", -0.3];
dic[68] = ["scaleX", 0.33];
//alpha
dic[81] = ["rotation", 3];
dic[69] = ["rotation", -3];
}
private function keyboard (e:KeyboardEvent):void{
if(e.type == KeyboardEvent.KEY_DOWN){
if(list.indexOf(e.keyCode) < 0 && dic[e.keyCode] != null){
list[list.length] = e.keyCode;
}
}else{
if(list.indexOf(e.keyCode) > -1 && dic[e.keyCode] != null){
list.splice(list.indexOf(e.keyCode),1)
}
}
}
private function drawShape (s:Shape, c:uint, r:int):Shape{
s.graphics.beginFill(c);
s.graphics.drawCircle(0,0,r);
s.graphics.endFill();
return s;
}
}
}
// << 37 /\ 38 >> 39 \/ 40
// a 65, w 87, d 68, s 83, q 81, e 69,