TextMate and mxmlc →← AS3 for developers and designers– Part 1: Creating a preloader

Array sorting

In AS2 we had Array.sortOn() and it worked fine if you had an array full of Objects with nice property names to sort on. But what happens when you have an array of MovieClips and you need to sort the array based on the Y axis? You’d have to pop/shift/unshift/slice/splice … wait … what?

In comes AS3. Array.sortOn("y", Array.NUMERIC); will easily change the indexes of the array if the y property changes. This comes in handy for a container MovieClip (or Sprite) that has a list of MovieClips (or Sprites) and that container is scrolling up and down. While it is scrolling, if the clip reaches the top of the stage, for example, you would want it to re-appear at the bottom.

The check is easy enough and moving the clip is also easy and now the mess of rearranging the array is also easy!

We are doing this so the array’s indexes mimic the order of the list. In doing so we can easily check the 1st element in the array (and the last for the bottom to top swap) to see if it is above the stage and … BAM! … set it’s y position to the bottom edge of the last element in the array.

Nice … and easy.

October 16th, 2007  by Stephen  /  5 Comments

Comments on “Array sorting”

  1. Yeah, that’s really cool. I think Senocular has posted some examples there: http://www.senocular.com/flash/tutorials/as3withflashcs3/?page=2

    Og2t on October 17th, 2007 at 4:59 am
  2. […] Sorting arrays in actionScript 3.0 has new features.  Check them out at big spaceshop labs. […]

    getswfy » Blog Archive » ActionScript 3.0 Array SortOn on October 17th, 2007 at 12:18 pm
  3. cool tip thanks guys :)

    Ben Cline on October 22nd, 2007 at 1:37 am
  4. The problem of sorting movieclips in AS2 is because the “_y”,”_x” stuff are not movieclips real parameters. The getter and setter functions mess up the whole thing. You can write your own comparing rule then apply it to just sort. That will solve the problem.
    http://www.adobe.com/support/flash/action_scripts/actionscript_dictionary/actionscript_dictionary068.html

    5566 on October 23rd, 2007 at 10:28 pm
  5. The problem with _x an _y in AS2 is what the numeric buddy said!
    The trick is to write a compare function like this
    //Priority for whom is in the top
    //Return -1 for “a” 1 for “b” and 0 for a “tie”
    function compare(a,b)
    {
    var ida:Number a.id //Some Comparing Key
    var idb:Number b.id //Some Comparing Key
    var ay:Number = a._y;
    var by:Number = b._y;

    if(ida>idb)
    {
    if(ayby)
    {
    var t:Number = a._y;
    a._y=b._y;
    b._y = t;
    }
    return 1;
    }

    return 0;
    }

    Eduardo on October 30th, 2007 at 5:04 pm