您的位置:首页 > 其它

[ActionScript 3.0] AS3 弹性运动

2015-08-20 17:50 169 查看
package com.views
{
import flash.display.Sprite;
import flash.events.Event;
import flash.geom.Point;

/**
* @author Frost.Yen
* @E-mail 871979853@qq.com
* @create 2015-8-20 上午11:16:11
*
*/
[SWF(width="800",height="600")]
public class ElasticMove extends Sprite
{
private const SPRING:Number=0.1;//弹性系数
private const FRICTION:Number=0.9;//摩擦系数
private const FEAR_DISTANCE:Number=150;//安全距离(小于该距离则发生躲避行为)
private const MAX_AVOID_FORCE:uint=10;//最大躲避速度
private var _destinationPoint:Point;//目标静止点(鼠标远离该物体时,物体最终会静止的坐标点)
private var _speed:Point=new Point(0,0);//速度矢量(_speed.x即相当于vx,_speed.y即相当于vy)
public function ElasticMove()
{
super();
drawStuff();
destinationPoint = new Point(300,300);
}
private function drawStuff():void {
//默认先画一个半径为10的圆
graphics.beginFill(Math.random() * 0xFFFFFF);
//graphics.beginFill(0xFFFFFF);
graphics.drawCircle(0, 0, 5);
graphics.endFill();
}
//只写属性(设置目标点)
public function set destinationPoint(value:Point):void {
_destinationPoint=value;
addEventListener(Event.ENTER_FRAME, enterFrameHandler);
}
protected function enterFrameHandler(e:Event):void {
moveToDestination();//先移动到目标点
avoidMouse();//躲避鼠标
applyFriction();//应用摩擦力
updatePosition();//更新位置
}
//以弹性运动方式移动到目标点
private function moveToDestination():void {
_speed.x += (_destinationPoint.x - x) * SPRING;
_speed.y += (_destinationPoint.y - y) * SPRING;
}
//躲避鼠标
private function avoidMouse():void {
var currentPosition:Point=new Point(x,y);//确定当前位置
var mousePosition:Point=new Point(stage.mouseX,stage.mouseY);//确实鼠标位置
var distance:uint=Point.distance(currentPosition,mousePosition);//计算鼠标与当前位置的距离
//如果低于安全距离
if (distance<FEAR_DISTANCE) {
var force:Number = (1 - distance / FEAR_DISTANCE) * MAX_AVOID_FORCE;//计算(每单位时间的)躲避距离--即躲避速率
var gamma:Number=Math.atan2(currentPosition.y- mousePosition.y,currentPosition.x- mousePosition.x);//计算鼠标所在位置与当前位置所成的夹角
var avoidVector:Point=Point.polar(force,gamma);//将极坐标转换为普通(笛卡尔)坐标--其实相当于vx = force*Math.cos(gamma),vy = force*Math.sin(gamma)
//加速 躲避逃开
_speed.x+=avoidVector.x;
_speed.y+=avoidVector.y;
}
}
//应用摩擦力
private function applyFriction():void {
_speed.x*=FRICTION;
_speed.y*=FRICTION;
}
//最终更新自身的位置
private function updatePosition():void {
x+=_speed.x;
y+=_speed.y;
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: