Search code examples
actionscript-3flashoverriding

Why can not get the override width and height in the container of Sprite extended object?


I have a object called Square that extends Sprite:

package {

    import flash.display.Sprite;
    import flash.geom.Point;

    public class Square extends Sprite {

        private var _point:Point = new Point(100, 100);

        public function Square() {
            // empty object
        }

        override public function set height(n:Number):void {
            _point.y = n;
        }

        override public function set width(n:Number):void {
            _point.x = n;
        }

        override public function get height():Number {
            return _point.y;
        }

        override public function get width():Number {
            return _point.x;
        }

    }
}

And in my Main document class, I've tried access width and height of square container, like this:

import flash.display.Sprite;

var container:Sprite = new Sprite();
var square:Square = new Square();

container.addChild(square);

trace(square.width, square.height); // 100 100
trace(container.width, container.height); // 0 0

I know my Square object is empty, but I override the width and height methods. I got it in the first trace, but not in the second, should it not work?


Solution

  • Overriding width and height DOES work and you can see that in:

    trace(square.width, square.height); // 100 100

    But I'm afraid it's not gonna work as you want it to in this example. Why trace(container.width, container.height); is giving you 0, 0 then? While the actual implementation it's not available I'm pretty sure it's not as simple as getting width and height of all children. If it was, what if you have 2 elements next to each other? Would the output be 200, 100 ? 100, 200? What if elements overlap each other (fully or partially only)?

    So instead of simply getting dimensions of the children flash is figuring it out by doing some other magic (sorry no idea how it is implemented) it is actually checking what's there. And as you said, your square object is empty, so that' why you're getting 0, 0.