[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; } } }
相关文章推荐
- [SoapUI] Loop a test with different sets of data
- linux系统下nodejs安装过程随记
- MySQL主从复制
- 有用的工具类网址
- php.2 php连接数据库实现增查
- Unity3D脚本自动添加tag和Layer
- Svn分支管理
- 服务器如何允许和禁止CNAME访问
- https封装类,支持get/post请求
- ios swift学习日记1-Swift 初见
- 【转】大型网站系统架构的演化
- sz与rz命令
- 算法题——投篮比赛获胜的概率
- 树莓派更改更新源
- TCP三次握手及关闭时的2MSL分析
- php5.5以下版本配置opcache
- archlinux的wiki非常强壮
- POJ 3162 Walking Race 树形DP+线段树
- Spring(二)——IoC
- 简述==和equles的区别