Skip to content


[AS 3] Simple Motion Tween To A Point

I just wanted to make a dynamically drawn box be animated to the center of the stage. I figure I can use this as a building block animation for a future project.

First we will use the DrawRectangle class to construct our object.

package
{
	import flash.display.Sprite;

	public class DrawRectangle extends Sprite
	{
		private var xPos:Number;
		private var yPos:Number;
		private var rWidth:Number;
		private var rHeight:Number;
		private var color:uint;

		public function DrawRectangle(xPos:Number=0,yPos:Number=0,rWidth:Number=10,rHeight:Number=10,color:uint=0x336699)
		{
			this.graphics.beginFill(color);
			this.graphics.drawRect(xPos,yPos,rWidth,rHeight);
			this.graphics.endFill();
		}
	}
}

Now our animation code which will be our Document Class called MoveToPoint

package
{
	import flash.display.Sprite;
	import flash.events.Event;

	public class MoveToPoint extends Sprite
	{
		private var box:DrawRectangle;
		private var speed:Number = 20;

		private var finalx:Number = stage.stageWidth / 2;
		private var finaly:Number = stage.stageHeight / 2;

		public function MoveToPoint()
		{
			init();
		}

		private function init():void
		{
			box = new DrawRectangle();
			addChild(box);
			addEventListener(Event.ENTER_FRAME, onEnterFrame);
		}

		private function onEnterFrame(event:Event):void
		{
			var dx:Number = finalx - box.x;
			var dy:Number = finaly - box.y;

			var angle:Number = Math.atan2(dy, dx);
			var vx:Number = Math.cos(angle) * speed;
			var vy:Number = Math.sin(angle) * speed;
			if (box.x + vx < finalx && box.y + vy < finaly)
			{
				box.x += vx;
				box.y += vy;
			}
			else
			{
				box.x = finalx;
				box.y = finaly;
			}
		}
	}
}

Posted in Actionscript 3, Animation Transitions.


0 Responses

Stay in touch with the conversation, subscribe to the RSS feed for comments on this post.



Some HTML is OK

or, reply to this post via trackback.