KeyboardEvent in ActionScript 3.0

キーボードのイベントって AS 1.0~2.0 は何気に swf を html 上でクリックしてアクティブにしていましたが、AS 3.0 ってきっちり明示しないとだめでしたね。この本には普通に書いてましたが、洋書を参考にビジュアライズしてたら見逃して、ちょっと悩んでしまったのでメモ。

swf コンテンツをクリック(自分は stage をクリックしたイベントを取得)したイベント内で stage の focus プロパティで動かしたいオブジェクト(interactiveObject)を"stage.focus = interactiveObject" してキーボードイベントを interactiveObject に対してアクティブにする。今回は interactiveObject 用に square class を設定しました。


参考スクリプトは下記に。


// 動かす為に四角形を作る
package {

import flash.display.Sprite;

public class Square extends Sprite {

private var w:Number;
private var h:Number;
private var color:uint;

public function Square(w:Number=100, h:Number=100, color:uint=0x000000) {
this.w = w;
this.h = h;
this.color = color;
init();
}

private function init():void {
graphics.beginFill(color);
graphics.drawRect(0, 0, w, h);
graphics.endFill();
}

}

}


// Keyboard イベント設定
package {

import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.*;
import flash.ui.Keyboard;

public class keyboardEx1 extends Sprite {

private var square:Square;
private var v:Number = 5;

public function keyboardEx1() {
init();
}

private function init():void {

stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;

square = new Square(200, 200);
square.x = (stage.stageWidth / 2) - (square.width / 2);
square.y = (stage.stageHeight / 2) - (square.height / 2);
square.focusRect = false;
addChild(square);

stage.addEventListener(MouseEvent.CLICK, clickHandler);
stage.addEventListener(KeyboardEvent.KEY_DOWN, onKeyDown);

}

private function clickHandler(evt:MouseEvent):void {
stage.focus = square;
}

private function onKeyDown(evt:KeyboardEvent):void {
switch(evt.keyCode) {
case Keyboard.LEFT:
square.x -= v;
break;
case Keyboard.RIGHT:
square.x += v;
break;
case Keyboard.UP:
square.y -= v;
break;
case Keyboard.DOWN:
square.y += v;
break;
default:
break;
}
}

}

}


【開発環境】
Flex Builder 2.01

ページの一番上へ移動

トラックバック

この記事へのトラックバック URL は下記の通りです。
http://www.convexstyle.net/mt/mt-tb.cgi/34

コメントの投稿

初めて投稿される方のコメントは管理者の承認が必要となります。ご了承ください。