R – How to stick position of one Sprite to another

actionscript-3flash

I have the following code:

if (i==0)
  sprites[i].y = 0;
else
  sprites[i].y = sprites[i-1].y + sprites[i-1].height; 

Every Sprite can have a different height. Height of a Sprite can change on user action.

When the height of some Sprite changes, I would like to update the position of other sprites accordingly.

I am looking for an object oriented (maybe event driven) solution. Any ideas?

Thanks

Best Solution

If you have good control over when the height of any given sprite is going to change then you can use a custom event. The setup would look something like this:

var UPDATED_EVENT:String = "updated";
var i:int = 0;
var count:int = sprites.length; // this is the length of your array

for (i = 0; i < count; i++) {
  sprites[i].addEventListener(UPDATED_EVENT, calc);
}

function calc(e:Event = null):void {
// here goes your positioning code
  for (i = 0; i < count; i++) {
    if (i==0)
      sprites[i].y = 0;
    else
      sprites[i].y = sprites[i-1].y + sprites[i-1].height;
  }
}

calc();

Then just make sure that whenever you change the height of one of your sprites you do something like this:

mySprite.dispatchEvent(new Event(UPDATED_EVENT));

If you're spread across multiple classes (and you probably should be) then you can make the UPDATED_EVENT string a const in a separate event class and access it from both.

That's still not a perfect solution for you - if you want, you can figure out which sprite is changing its height and only recalc the sprites that come after it, and that'll make your code more efficient - but it beats calling an enterframe event every time.

Now, if you were using Flex you'd have even more tools at your disposal - you could probably use databinding to automate almost all of this, or at least use the changed event to automatically dispatch events for you, but that's neither here nor there!

Related Question