2012-08-09 43 views
0

我想要创建一组随机对象以便在循环中落下舞台。在AS3中生成随机下降的对象

到目前为止,我已经创建了一个测试对象落在一个随机的x坐标。我无法处理如何循环下降的函数,因此对象的多个实例不断下降。

var randomX:Number = Math.random() * 800; 

test_mc.x = randomX; 
test_mc.y = 0; 

var speed:Number = 10; 

test_mc.addEventListener(Event.ENTER_FRAME, moveDown); 

function moveDown(e:Event):void 
{ 
e.target.y += speed; 

if(e.target.y >= 480) 
{ 
     test_mc.removeEventListener(Event.ENTER_FRAME, moveDown); 
} 
} 

回答

2

指我的一个落雪效果代码。

雪的起始位置都是随机的,几乎和真正的落雪情况一样的效果。如果你运行你会惊讶。

雪是我的自定义影片剪辑(白色圆形,宽15,高15)

这里是我的演示:SnowEffect

这里是我的源:SnowEffect Down

this.addEventListener(Event.ENTER_FRAME, onEnter); 

function onEnter(e: Event):void { 

    var s: Snow = new Snow(); 
    s.x=550*Math.random(); 
    s.y=-20; 
    s.width=s.height=1+9*Math.random();// 1 ~ 9 

    s.xSpeed=-2+4*Math.random();// -2 ~ 2 
    s.ySpeed=1+4*Math.random();// 1 ~ 5 

    s.at = -0.001 -0.001*Math.random(); 
    s.vt = 0; 
    this.addChild(s); 

    s.addEventListener(Event.ENTER_FRAME, onSnowEnter); 
} 

function onSnowEnter(e: Event):void { 
    var s:Snow=e.currentTarget as Snow; 
    s.x+=s.xSpeed; 
    s.y+=s.ySpeed; 


    if (s.y>=480) { 
     s.addEventListener(Event.ENTER_FRAME, onMeltingEnter); 
    } 
} 

function onMeltingEnter(e: Event): void { 
    var s:Snow=e.currentTarget as Snow; 
    this.addChild(s); 
    s.removeEventListener(Event.ENTER_FRAME, onSnowEnter); 
    s.vt += s.at; 
    s.alpha += s.vt; 
    if (s.alpha <=0){ 
     s.removeEventListener(Event.ENTER_FRAME, onMeltingEnter); 
     this.removeChild(s); 
    } 

} 
1

通过数组创建一个组对象,将它们添加到一个数组,然后循环:

var numOfObjects:int = 10; 
var fallingObjectArray:Array = []; 
var speed:Number = 10; 

// Add 10 falling objects to the display and to the array 
for(var i:int = 0; i < numOfObjects; i++) { 
    var fallingObject:Sprite = new Sprite(); 
    fallingObject.graphics.beginFill(0xFF0000); 
    fallingObject.graphics.drawCircle(0, 0, 15); 
    fallingObject.graphics.endFill(); 
    addChild(fallingObject); 
    fallingObject.x = Math.random() * stage.stageWidth; 
    fallingObjectArray.push(fallingObject); 
} 

addEventListener(Event.ENTER_FRAME, moveDown); 

function moveDown(e:Event):void 
{  
    // Go through all the objects in the array and move them down 
    for each(var fallingObject in fallingObjectArray) { 
     fallingObject.y += speed; 
     // If the object is past the screen height, remove it from display and array 
     if(fallingObject.y+fallingObject.height >= stage.stageHeight) { 
     removeChild(fallingObject); 
     fallingObjectArray.splice(fallingObjectArray.indexOf(fallingObject), 1); 
     } 
    } 
    // Once all objects have fallen off the screen, remove the listener 
    if(fallingObjectArray.length <= 0) { 
     removeEventListener(Event.ENTER_FRAME, moveDown); 
    } 
} 

上面的代码只是用红色圆圈 - 你将不得不使用你拥有的任何图像相反(除非你喜欢红色圆圈......)。