Search code examples
actionscript-3movieclipbounds

AS3 MovieClip getRealBounds


As you well know in as3 we have a getBounds() method which returns the exact dimension and coordinates of the movieclip in the DisplayObject container we want. Fact is that these data are calculated based on the graphics in their state in the MC at the frame it is while getBounds() is called.

What I want is the REAL bounds rectangle, that is the larger rectangle that the WHOLE animated movieclip will take in its container.
I thought of two ways:
1 - a flash built-in method that I don't know
2 - going through every frame always getting the bounds and finally returning the biggest (but what if it's a long animation? should I wait for it to play completely before I can get what I want?)

I hope I've been clear. If you need examples, let me know!


Solution

  • You can iterate through each frame without having to wait for the animation to play:

    Let's say your clip is called bob:

    var lifetimeBounds:Rectangle = new Rectangle();
    bob.gotoAndStop(1);
    for(var i:int=1;i<=bob.totalFrames;i++){
        lifetimeBounds.width = Math.max(lifetimeBounds.width, bob.width);
        lifetimeBounds.height = Math.max(lifetimeBounds.height, bob.height);
        lifetimeBounds.x = Math.min(lifetimeBounds.x, bob.x);
        lifetimeBounds.y = Math.min(lifetimeBounds.y, bob.y);
        bob.nextFrame();
    }
    
    bob.gotoAndStop(1); //reset bob back to the beginning
    

    It's more CPU taxing (so I'd recommend not using it if the above works for your situation), but you could also use getBounds() in the example above and compare the returned rectangle against the lifetimeBounds rectangle:

    var tempRect:Rectangle;
    var lifetimeBounds:Rectangle = new Rectangle();
    bob.gotoAndStop(1);
    for(var i:int=1;i<=bob.totalFrames;i++){
        tmpRect = bob.getBounds(this);
        lifetimeBounds.width = Math.max(lifetimeBounds.width, tempRect.width);
        lifetimeBounds.height = Math.max(lifetimeBounds.height, tempRect.height);
        lifetimeBounds.x = Math.min(lifetimeBounds.x, tempRect.x);
        lifetimeBounds.y = Math.min(lifetimeBounds.y, tempRect.y);
        bob.nextFrame();
    }