localToGlobal
— 11th February 2009
Right so you’ve got an hierarchy of nested movieclips (or sprites) and you're rotating each separately to get a kind chain effect like the different moving parts of an arm or a leg. At the end of your leg you’ve got a foot (and maybe even toes) and there you are with your leg flailing around like a dervish on heat! Perfect. Now you need to workout the x and y coordinates of one of those toes, so you can... errr... make lasers fire out of it whenever the user sneezes, right? (am I right?).Anyway, if you want those coordinates you can't just say toe.x and toe.y that’s not going to work, because those coordinates are local to those toes, or at least local to the foot movieclip you’ve attached them to. So what do you do? Well, you might find yourself iterating back through the hierarchy of movieclips finding out the x and y and adding them up and stuff. Phew! It’s hard work, but do-able. But wait, then you’ve got to degotiate all that rotation. Gah! What was that stuff I read about coordinate rotation? Oh god please don't send me back to the dark place!!!Luckily you're saved all this by using the helpful function localToGlobal. It takes a Point which is local to your object and translates it to a Point which is relative the global object (let’s call that the Stage).You use it like this:
var p:Point = new Point(toe.x,toe.y);var np:Point = toe.parent.localToGlobal(p);What I'm doing there is finding out the actual global position of the toe. So I create a new Point and pass in the x and y coordinates of toe. Then I can find out where actually it is on the stage by passing that Point into the function localToGlobal.Remember the key point here is that it’s the toe's parent (the foot?) which has to call the function because of course the x and y coordinates of toe are relative to the foot aren't they.