Track
/**
* Copyright jaydenhp ( http://wonderfl.net/user/jaydenhp )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/x5yp
*/
package {
import flash.display.Sprite;
import flash.display.MovieClip;
import flash.display.DisplayObject;
import flash.events.Event;
import flash.events.MouseEvent;
public class FlashTest extends Sprite {
private var mouse:Sprite;
private var target:Sprite;
private var balls:Array = [];
private var ballNum:int = 4000;
public function FlashTest() {
// write as3 code here.
for (var i:int = 0; i <= ballNum; i++)
{
var ball:Sprite = createBall(3);
addChild(ball);
ball.x = Math.random() * stage.stageWidth;
ball.y = Math.random() * stage.stageHeight;
balls.push(ball);
}
mouse = createBall(6);
addChild(mouse);
target = mouse;
addEventListener(Event.ENTER_FRAME, onFrame);
stage.addEventListener(MouseEvent.MOUSE_DOWN, onDown);
stage.addEventListener(MouseEvent.MOUSE_UP, onUp);
}
private function onDown(e:MouseEvent):void{
target = null;
}
private function onUp(e:MouseEvent):void{
target = mouse;
}
private function onFrame(e:Event):void
{
mouse.x = this.mouseX;
mouse.y = this.mouseY;
for (var i:int = 0; i <= ballNum; i++)
{
Track(target, balls[i], 5, 3, 1);
}
}
private function createBall(r:int):Sprite
{
var b:Sprite = new Sprite();
b.graphics.beginFill(Math.random() * int.MAX_VALUE);
b.graphics.drawRect(-2, -2, 2, 2);
b.graphics.endFill();
return b;
}
public function Track(target:DisplayObject,mc:DisplayObject,speed:Number,omega:Number=0,dir:int=1):void{
if(!target){
moveDirectly(mc,speed * Math.cos(mc.rotation*Math.PI/180));
}
else{
var dx:Number = mc.x - target.x;
var dy:Number = mc.y - target.y;
//target与y轴的夹角
var angle:Number = (270 + Math.atan2(dy, dx)*180/Math.PI)%360;
//target与mc的夹角
var crtangle:Number = (angle - mc.rotation + 360)%360;
//判断mc旋转方向
var dir:int = crtangle<=180?1:-1;
if(omega)
mc.rotation = (crtangle<180 && crtangle>omega || crtangle>180 && 360-crtangle>omega)? (mc.rotation+omega*dir) : angle;
else
mc.rotation = angle;
}
mc.x += speed*Math.sin(mc.rotation*Math.PI/180);
mc.y -= speed*Math.cos(mc.rotation*Math.PI/180);
}
public function moveDirectly(sprite:DisplayObject,vspeed:Number):void{
sprite.y += vspeed;
}
}
}