底下分成兩部份,先介紹as2.0早期寫法 ,再為各位介紹as3.0 有3種鍵盤寫法!
( as2.0已經不推薦使用囉 )
不論那一種AS3.0寫法 以下都只能做一個事件方向的偵測 ,
兩個方向量無法同時被觸發, 意思就是當然按下 左 & 上時 它只會觸發其一,這解決方法在下一節討論
早期AS2.0寫法
//在onEnterFrame status :
if (Key.isDown(Key.LEFT)) {
xspeed -= power;
}
if (Key.isDown(Key.RIGHT)) {
xspeed += power;
}
if (Key.isDown(Key.UP)) {
yspeed -= power;
}
if (Key.isDown(Key.DOWN)) {
yspeed -= power;
}
xspeed *= friction; //磨擦力
yspeed *= friction;
_y += yspeed;
_x += xspeed;
AS3.0鍵盤事件寫法 , 都已改為事件監聽方法, 監聽key是否DOWN 或UP
3.0鍵盤寫法1:
stage.addEventListener(Event.ENTER_FRAME, report_loop);
//場景進入立刻 ENTER_FRAME(跟onEnterFrame同道理) 不停的跑report_loop 函數
stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);
//一開始 "場景" 監聽鍵盤是否被按下或放開事件
//該report_loop不停的被觸發 接收 keyDown 所得到的 xspeed 與 yspeed 值 來做磨擦力與物件位移
function report_loop(event:Event):void {xspeed*=friction;yspeed*=friction;mc.y += yspeed;mc.x += xspeed;}
//當事件觸發 鍵盤按下 就觸發以下條件
function reportKeyDown(event:KeyboardEvent):void { if (event.keyCode==Keyboard.RIGHT) { xspeed+=power; } if (event.keyCode==Keyboard.LEFT) { xspeed-=power; } if (event.keyCode==Keyboard.UP) { yspeed-=power; } if (event.keyCode==Keyboard.DOWN) { yspeed+=power; } }//keyDown
3.0鍵盤寫法2:
stage.addEventListener(Event.ENTER_FRAME, report_loop);stage.addEventListener(KeyboardEvent.KEY_DOWN, reportKeyDown);stage.addEventListener(KeyboardEvent.KEY_UP, reportKeyUp);function reportKeyDown(event:KeyboardEvent):void {objKeyboard.pressed=true;objKeyboard.keyCode=event.keyCode;}function reportKeyUp(evt:KeyboardEvent): void{objKeyboard.pressed = false;objKeyboard.keyCode = null;}
//一樣分為KEY DOWN與UP,
//不同的是,當DOWN觸發的事件內容,透過自定參數來判斷是否按下
function reportKeyUp(evt:KeyboardEvent): void{objKeyboard.pressed = false;objKeyboard.keyCode = null;}
var power:Number=0.8;var yspeed:Number=0;var xspeed:Number=0;var friction:Number=0.9;var objKeyboard:Object;objKeyboard={pressed:true,keyCode:null};
function report_loop(event:Event):void {xspeed*=friction; yspeed*=friction; mc.y+=yspeed; mc.x+=xspeed; if (objKeyboard.pressed) { //自定參數判斷是否按下 switch (objKeyboard.keyCode) { //利用 switch 判斷key值 case 37 : xspeed += power; break; case 39 : xspeed -= power; break; case 38 : yspeed += power; break; case 40 : yspeed -= power; break; } } }
3.0鍵盤寫法3:
//以下寫法大家想必都非常熟悉 ,很像 AS2.0 寫法
if (objKeyboard.keyCode==37) {xspeed+=power;}if (objKeyboard.keyCode==39) {xspeed-=power;}if (objKeyboard.keyCode==38) {yspeed+=power;}if (objKeyboard.keyCode==40) {yspeed-=power;}
沒有留言:
張貼留言