1 package com.views 2 { 3 import flash.display.Sprite; 4 import flash.events.Event; 5 import flash.geom.Point; 6 7 /** 8 * @author Frost.Yen 9 * @E-mail 871979853@qq.com 10 * @create 2015-8-20 上午11:16:11 11 * 12 */ 13 [SWF(width="800",height="600")] 14 public class ElasticMove extends Sprite 15 { 16 private const SPRING:Number=0.1;//彈性係數 17 private const FRICTION:Number=0.9;//摩擦係數 18 private const FEAR_DISTANCE:Number=150;//安全距離(小於該距離則發生躲避行爲) 19 private const MAX_AVOID_FORCE:uint=10;//最大躲避速度 20 private var _destinationPoint:Point;//目標靜止點(鼠標遠離該物體時,物體最終會靜止的座標點) 21 private var _speed:Point=new Point(0,0);//速度矢量(_speed.x即至關於vx,_speed.y即至關於vy) 22 public function ElasticMove() 23 { 24 super(); 25 drawStuff(); 26 destinationPoint = new Point(300,300); 27 } 28 private function drawStuff():void { 29 //默認先畫一個半徑爲10的圓 30 graphics.beginFill(Math.random() * 0xFFFFFF); 31 //graphics.beginFill(0xFFFFFF); 32 graphics.drawCircle(0, 0, 5); 33 graphics.endFill(); 34 } 35 //只寫屬性(設置目標點) 36 public function set destinationPoint(value:Point):void { 37 _destinationPoint=value; 38 addEventListener(Event.ENTER_FRAME, enterFrameHandler); 39 } 40 protected function enterFrameHandler(e:Event):void { 41 moveToDestination();//先移動到目標點 42 avoidMouse();//躲避鼠標 43 applyFriction();//應用摩擦力 44 updatePosition();//更新位置 45 } 46 //以彈性運動方式移動到目標點 47 private function moveToDestination():void { 48 _speed.x += (_destinationPoint.x - x) * SPRING; 49 _speed.y += (_destinationPoint.y - y) * SPRING; 50 } 51 //躲避鼠標 52 private function avoidMouse():void { 53 var currentPosition:Point=new Point(x,y);//肯定當前位置 54 var mousePosition:Point=new Point(stage.mouseX,stage.mouseY);//確實鼠標位置 55 var distance:uint=Point.distance(currentPosition,mousePosition);//計算鼠標與當前位置的距離 56 //若是低於安全距離 57 if (distance<FEAR_DISTANCE) { 58 var force:Number = (1 - distance / FEAR_DISTANCE) * MAX_AVOID_FORCE;//計算(每單位時間的)躲避距離--即躲避速率 59 var gamma:Number=Math.atan2(currentPosition.y- mousePosition.y,currentPosition.x- mousePosition.x);//計算鼠標所在位置與當前位置所成的夾角 60 var avoidVector:Point=Point.polar(force,gamma);//將極座標轉換爲普通(笛卡爾)座標--其實至關於vx = force*Math.cos(gamma),vy = force*Math.sin(gamma) 61 //加速 躲避逃開 62 _speed.x+=avoidVector.x; 63 _speed.y+=avoidVector.y; 64 } 65 } 66 //應用摩擦力 67 private function applyFriction():void { 68 _speed.x*=FRICTION; 69 _speed.y*=FRICTION; 70 } 71 //最終更新自身的位置 72 private function updatePosition():void { 73 x+=_speed.x; 74 y+=_speed.y; 75 } 76 } 77 }