Skip to main content
Known Participant
December 26, 2009
Answered

Animating Instances of an Object Created by a For Loop

  • December 26, 2009
  • 1 reply
  • 882 views

I'v been toying with this for a few weeks now and I'm trying to find the best way to animate several instances of an object created by a for loop thru an ENTER_FRAME function. When the function runs only 1 of the 3 instances that were created animates.

var balloonArray:Array = new Array();
var balloon: hotAirBalloon;
var xVel: Number = -3;
var yVel: Number = -4;

addEventListener(Event.ENTER_FRAME, startBalloons)

for(var i:int=0; i<3; i++)
         {
             balloon = new hotAirBalloon;
             addChild(balloon);
             //balloonArray.push(balloon) // tried pushing the instances in an array
             setBalloons();
         }

function setBalloons():void
     {
         balloon.x = randomRange(200, 400);
         balloon.y = randomRange(400, 550)
         balloon.scaleX=balloon.scaleY=randomRange(0.3, 1);
     }

function startBalloons(evt:Event):void
    {
        balloon.y += yVel// this only animates one instance

        balloon.x += xVel
     }

I also tried pushing the object into an array in the for loop and using this balloonArray.y += yVel in the ENTER_FRAME function and I get an error saying that a term is undefined. I know there is a simple way to achieve this. Thanks.

This topic has been closed for replies.
Correct answer kglad

using splice(i,1) works well to remove the ith array element.  generally, you should loop through arrays from end to start if you remove array elements in a for-loop.

1 reply

kglad
Community Expert
Community Expert
December 26, 2009

try:


var balloonArray:Array = new Array();
var balloon: hotAirBalloon;
var xVel: Number = -3;
var yVel: Number = -4;

addEventListener(Event.ENTER_FRAME, startBalloons)

for(var i:int=0; i<3; i++)
         {
             balloon = new hotAirBalloon();
             addChild(balloon);
             balloonArray.push(balloon) // tried pushing the instances in an array
             setBalloons();
         }

function setBalloons():void
     {
         balloon.x = randomRange(200, 400);
         balloon.y = randomRange(400, 550)
         balloon.scaleX=balloon.scaleY=randomRange(0.3, 1);
     }

function startBalloons(evt:Event):void
    {

for(i=0;i<balloonArray.length;i++){
        balloonArray.y += yVel// this only animates one instance

        balloonArray.x += xVel

}

// at some point you should remove array elements and, at some point you should terminate your enterframe loop.
     }

Known Participant
December 27, 2009

Thanks that was helpful. What's the best way to remove the array elements?

kglad
Community Expert
kgladCommunity ExpertCorrect answer
Community Expert
December 27, 2009

using splice(i,1) works well to remove the ith array element.  generally, you should loop through arrays from end to start if you remove array elements in a for-loop.