ActionScript3.0でクリックした点まで物体を動かすサンプル

最近,ActionScriptにハマっています.物体を移動させるライブラリはたくさんあるのですが,やはり細かい動きをさせたいときは,自分でコードを書くのが一番です.ということで,クリックしたところまで物体を動かすサンプルを書いてみました.二つのファイル(main.asとCircle.as)から成っています.この二つのファイルは同じフォルダに配置してコンパイルして下さい.

実行例はこちらです.

ソースはこちら.これはmain.as.

// main.as
package
{
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import Circle;
	
	public class actions extends Sprite
	{
		
		private var _self:Circle;
		
		public function actions()
		{
			this._self = new Circle();
			addChild(this._self);
			
			this.stage.addEventListener(MouseEvent.CLICK, _move);

		}

		private function _move(e:MouseEvent):void
		{
			this._self.moveTo({x:e.stageX, y:e.stageY});
		}
		
	}
}

こっちはCircle.asです.

//Circle.as
package {
	import flash.display.Sprite;
	import flash.events.Event;

	public class Circle extends Sprite
	{
		
		public var from:Object;
		public var to:Object;
		public var speed:Number = 10;
		
		public function Circle():void
		{
			_drawCircle();
		}
		
		// 円を描く
		private function _drawCircle():void
		{
			this.graphics.beginFill(0xFFCC00);
			this.graphics.drawCircle(50, 50, 50);
			this.graphics.endFill();
		}
		
		// 現在地から,指定したところまで移動する
		public function moveTo(to:Object):void{
			this.from = {x:x, y:y}
			this.to = to;
			this.addEventListener(Event.ENTER_FRAME, _moveTo);
		}
		
		private function _moveTo(e:Event):void
		{
			
			// 目的地までの距離を測定する
			var diffX:Number = Math.abs(this.to.x - this.from.x);
			var diffY:Number = Math.abs(this.to.y - this.from.y);
			
			// 移動スピードを設定する
			this.speed = _ease(this.speed, diffX, diffY);
			
			
			// 目的地(付近)に着いたら移動をやめる
			if (diffX < this.speed && diffY < this.speed){
				this.removeEventListener(Event.ENTER_FRAME, _moveTo);
			}
			
			// x座標が目的地(付近)に到達していない場合,fromを更新
			if (diffX > this.speed) {
			
				if (this.from.x < this.to.x) {
					this.from.x += this.speed;
				} else {
					this.from.x -= this.speed;
				}

			}
			
			// y座標が目的地(付近)に到達していない場合,fromを更新
			if (diffY > this.speed) {
			
				if (this.from.y < this.to.y) {
					this.from.y += this.speed;
				} else {
					this.from.y -= this.speed;
				}

			}
			
			// 更新したfromを新たな現在地に設定する
			this.x = this.from.x;
			this.y = this.from.y;

		}
		
		// 移動スピードを調節する(まだ適当)
		public function _ease(speed:Number, diffX:Number, diffY:Number):Number
		{
			return Math.max(diffX, diffY) / 10;
		}
	}
}