4 Replies Latest reply on Mar 30, 2011 5:57 AM by kglad

    Good way to manage sprite layers via actionscript?

    DaveGallant Level 1

      In my app, I will have many sprites that move around.

       

      Let's assume they are balls, and I have 50 of them on the stage.

       

      the "background" looks like a perspective box.

       

      As the balls move vertically on the stage, they need to move "back" and as they move down they come "forward", giving the illusion of depth.

       

      Right now, the only way I know how to do this is via the setChildIndex function.

       

      so what I do is create an array to remember all my display objects and balls.

       

      like this:

       

       

      var arrBalls:Array = new Array();

       

      for(var i:int = 0; i < 50; i++){

       

           var NewBall:clsBall = new clsBall();

           var disp:DisplayObject = this.addChild(NewBall);

       

           arrBalls.push([NewBall.y, NewBall, disp]);

      }

       

       

       

      Then when ever a ball moves vertically in any direction, I call this function:

       

       

      function ReorderSprites():void

      {

                 var i:Number;

                // set the first element of each sub array to the y value fo the ball

                for (i = 0; i < arrBalls.length; i++) {
                      arrBalls[i][0] = arrBalls[i][1].y;
                  }

       

                // sort the array based on the first value of the sub array, thus giving me the order they are to appear from back to front

                  arrBalls.sortOn("0",Array.NUMERIC);

       

                 // reorder the balls.
                  for (i = 0; i < arrBalls.length; i++) {
                      this.setChildIndex(arrBalls[i][2], i +1);
                  }

       

      }

       

       

       

      Now, while this doesn't techincally, work, it's slow as hell... especially when you start getting a large number of balls moving

       

      Is there are better way to do this?