ITeye博客

弹性运动(四):多目标点弹性运动

china34420 · 2010-08-10 11:47 · AS3动画编程 · 编程语言 · Markdown

package 
{
	import flash.display.Sprite;
	import flash.events.MouseEvent;
	import flash.events.Event;
	import flash.display.Graphics;
	
	/**
	 * ...多目标点弹性运动
	 * @author zkl
	 * 来自:Action Script3.0 Animation
	 */
	public class MultiSpring extends Sprite
	{
		private var ball:Ball;
		//private var handle:Ball;
		private var handles:Array;
		private var numHandle:Number = 3;
		private var spring:Number = 0.2;
		private var friction:Number = 0.8;
		private var gravity:Number = 8;
		
		public function MultiSpring():void
		{
			init();
		}
		private function init():void
		{
			ball = new Ball(20);
			addChild(ball);
			
			handles = new Array;
			for (var i:int = 0; i < numHandle; i++ ) {
				var handle:Ball = new Ball(10, 0x0000ff);
				addChild(handle);
				handle.x = Math.random() * stage.stageWidth;
				handle.y = Math.random() * stage.stageHeight;
				handle.addEventListener(MouseEvent.MOUSE_DOWN, mouseDown);
				handles.push(handle);
			}
			addEventListener(Event.ENTER_FRAME, EnterFrame);
			addEventListener(MouseEvent.MOUSE_UP, mouseUp);
			
		}
		private function EnterFrame(e:Event):void
		{
			for (var i:int = 0; i < numHandle; i++ ) {
				var handle:Ball = handles[i] as Ball;
				var dx:Number = handle.x - ball.x;
				var dy:Number = handle.y - ball.y;
				ball.vx += dx * spring;
				ball.vy += dy * spring;
			}
			
			//ball.vy += gravity;
			
			ball.vx *= friction;
			ball.vy *= friction;
			
			ball.x += ball.vx;
			ball.y += ball.vy;
			
			graphics.clear();
			graphics.lineStyle(1);
			for (i = 0; i < numHandle; i++ ) {
				graphics.moveTo(ball.x, ball.y);
				graphics.lineTo(handles[i].x, handles[i].y);
			}
		}
		
		private function mouseDown(e:MouseEvent):void
		{
			e.target.startDrag();
		}
		private function mouseUp(e:MouseEvent):void
		{
			stopDrag();
		}
		
	}
	
}

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。