problem with getBounds as3

hello (sorry for my bad english)
i draw 5 sections of circle and put them in movieClip and then rotate them to create circle
and i want to draw a rect around this circle but getBounds width and height not correct
my code:

import flash.display.MovieClip;
import flash.display.Sprite;

var shape:MovieClip=new MovieClip();
addChild(shape);
shape.x = shape.y = 80;
for (var c:uint = 0; c < 5; c++)
{
    var m:MovieClip=new MovieClip();
    shape.addChild(m);
}

for (var i:uint = 0; i < 5; i++)
{
    var s:MovieClip = MovieClip(shape.getChildAt(i));
    s.graphics.clear();
    s.graphics.lineStyle(0,0);
    s.graphics.beginFill(0xffffff);

    for (var j:uint= 0; j <= 360/5; j++)
    {
        s.graphics.lineTo(30 * Math.cos(j * (Math.PI / 180)), -  30  * Math.sin(j * (Math.PI / 180)));
    }
    s.rotation =  -  i * (360 / 5);
    s.x = s.y = 30;
}

var Bound:Sprite=new Sprite();
addChild(Bound);
Bound.graphics.lineStyle(1,0);
Bound.x = Bound.y = shape.x;
Bound.graphics.drawRect(0,0,shape.getBounds(shape).width,shape.getBounds(shape).height);

A couple of things. First, you generally want to use the form object.getBounds(object.parent) since that will include any transforms applied to the object. But since you’re not doing anything with shape here, and you’re already offsetting Bound (which, conventionally, should be lowercase ;)), its ok.

Next, you’re ignoring the x,y properties of the getBounds rect. Without it, you’re not including any of the content in the “negative” space of the object.

var bounds = shape.getBounds(shape);
Bound.graphics.drawRect(bounds.x, bounds.y, bounds.width, bounds.height);

Finally, and most important, is that you may be seeing that the bounds you’re drawing is bigger than the shape you’re seeing. This is because getBounds gets the bounds of other objects’ bounds. And if you rotate an object - which you are doing with your s clips - its bounds rotates. To see whats really going on, you can include this at the bottom of your script:

for (i = 0; i < 5; i++)
{
    s = MovieClip(shape.getChildAt(i));
	var b = s.getBounds(s);
	s.graphics.lineStyle(1, 0xFF0000);
	s.graphics.drawRect(b.x,b.y,b.width,b.height);
}

The bounding boxes of each one of your wedges gets rotated with the wedges and becomes part of what makes up the boundaries of the overall shape.

The easiest way to fix this is to draw your wedges with the rotation in the drawing rather than rotating the clips themselves.

2 Likes