[ActionScript 3.0] AS3.0 对象在矩形范围随机运动

package com.views
{ import flash.display.Bitmap;
import flash.display.MovieClip;
import flash.display.Sprite;
import flash.events.Event; /**
* @author:Frost.Yen
* @E-mail:871979853@qq.com
* @create: 2016-7-7 下午2:33:56
*
*/
public class LogoView extends Sprite
{
private var _stageW:Number = 1920;
private var _stageH:Number = 1080;
private var _mc:MovieClip = new MovieClip();
public function LogoView(bmp:Bitmap)
{
_mc.addChild(bmp);
bmp.x = -bmp.width*0.5;
bmp.y = -bmp.height*0.5;
initLogo();
} private function initLogo():void{ //随机位置
_mc.x = Math.random()*_stageW;
_mc.y = Math.random()*_stageH;
//随机速度和方向
Math.random()>0.5?_mc.speedX = Math.random()*5+1 : _mc.speedX = -1 * Math.random()*5+1
Math.random()>0.5?_mc.speedY = Math.random()*5+1 : _mc.speedY = -1 * Math.random()*5+1
//因为logo的坐标原点是logo的中心,所以用该函数用来调整logo位置,防止移出边界
adjustBall(_mc);
//添加logo到显示列表
addChild(_mc);
//用ENTER_FRAME侦听器使logo运动
//startMove();
} private function adjustBall(mc:MovieClip):void{
if(mc.x > _stageW-mc.width/2){mc.x = _stageW-mc.width/2;}
if(mc.x < mc.width/2){mc.x = mc.width/2};
if(mc.y > _stageH-mc.height/2){mc.y = _stageH-mc.height/2;}
if(mc.y < mc.height/2){mc.y = mc.height/2;}
} private function onEnterFrame(evt:Event):void{
//改变logo的坐标让小球运动
evt.target.x += evt.target.speedX;
evt.target.y += evt.target.speedY;
//检测logo是否碰到舞台边界
if(evt.target.x >= _stageW-evt.target.width/2 || evt.target.x <= evt.target.width/2){
evt.target.speedX *= -1;
}
if(evt.target.y >= _stageH-evt.target.height/2 || evt.target.y <= evt.target.height/2){
evt.target.speedY *= -1;
}
}
public function startMove():void
{
_mc.addEventListener(Event.ENTER_FRAME,onEnterFrame);
}
public function stopMove():void
{
_mc.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
}
}
}
上一篇:位图字体生成工具Bitmap Font Generator的使用


下一篇:js 之 this call apply