彩音 - Adobe AIR - 研究室:XION -Adobe AIR-laboratory
ベクトルの向きと大きさ normalize()

normalize() は、ベクトルの向きはそのままでベクトルの大きさを変更するメソッドである。以下の例ではフィールドをクリックするとその方向にインスタンスが移動する。どの向きに進む場合も移動の速度は speed で指定した速さになる。
インスタンス座標とクリックされたポイントのグローバル座標から進む方向のベクトルを判定し、ベクトルサイズを normalize() を使い speed の大きさに変換する。mc1 が進む方向に向くように Math.atan2() で2点間の角度を計算し、インスタンスを回転させる。


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" width="600" height="256" initialize="init()">
<mx:Script>
<![CDATA[
import mx.core.UIComponent;
private var container:UIComponent = new UIComponent();
private var mc1:Sprite = new Sprite();
private var vector:Point = new Point();
private var speed:int = 10;
private var pt1:Point;
private var pt2:Point;
private function init():void {
addChild(container);
mc1.graphics.beginFill(0xffffff);
mc1.graphics.moveTo(10,0);
mc1.graphics.lineTo(-10, 10);
mc1.graphics.lineTo(-10, -10);
mc1.graphics.endFill();
container.addChild(mc1);
application.addEventListener(MouseEvent.CLICK, onClick);
mc1.addEventListener(Event.ENTER_FRAME, enterFrame);
}
private function onClick(event:MouseEvent):void {
pt1 = new Point(mc1.x, mc1.y);
pt2 = new Point(event.stageX, event.stageY);
vector = pt2.subtract(pt1);
vector.normalize(speed);
mc1.rotation = Math.atan2(vector.y, vector.x)*180/Math.PI;
}
private function enterFrame(event:Event):void {
mc1.x += vector.x;
mc1.y += vector.y;
if (mc1.x < 0) {
mc1.x = application.width;
} else if (mc1.x >application.width) {
mc1.x = 0;
}
if (mc1.y < 0) {
mc1.y = application.height;
} else if (mc1.y > application.height) {
mc1.y = 0;
}
}
]]>
</mx:Script>
</mx:Application>

索引