Search code examples
actionscript-3flash

Can't change width and height values of a shape in AS3


This is my Entity class.

package  {
    import flash.display.Shape;
    public class Entity extends Shape{
        public var color:int;
        public function 
        Entity(xA:Number,yA:Number,widthA:Number,heightA:Number,c:int) {
            this.x=xA;
            this.y=yA;
            this.width=widthA;
            this.height=heightA;
            color=c;
            graphics.beginFill(color);
            graphics.drawRect(x,y,width,height);
            graphics.endFill();
        }
    }
}

And this is my main code.

var rectangle:Entity = new Entity(10,10,100,100,0xFF0000);
addChild(rectangle);
trace(rectangle.x+" "+rectangle.y+" "+rectangle.width+" "+rectangle.height+" "+rectangle.color);

And what I'm expecting is for widthA and heightA to change the width and height of the shape, but when I run the code I get this

10 10 0 0 16711680

From the trace, which indicates the x and y position are changing but not the height. Why is this?


Solution

  • The problem is that you're setting the width and height of a display object with no graphics. Since its width and height at that point are zero, you're asking Flash to set the scale values to infinity. There's no way an empty display object can have width and height other than zero.

    Try this:

            this.x=xA;
            this.y=yA;
            color=c;
            graphics.beginFill(color);
            graphics.drawRect(0,0,widthA,heightA); // I suspect you don't want x and y here.
            graphics.endFill();
    

    The width and height will be set automatically.