Question

I've seen code where an object can be added relative to another but I can't get it to work. I'm just trying to draw a rectangle and then add another smaller rectangle relative to the first

public var rectangle:Sprite = new Sprite();
public var other:Sprite = new Sprite();

rectangle.graphics.beginFill(0xFF0000);
rectangle.graphics.drawRect(250, 10, 100, 100);
rectangle.graphics.endFill();

other.graphics.beginFill(0x00FF00);
other.graphics.drawRect(0, 0, 50, 50);
other.graphics.endFill();
rectangle.addChild(other);
this.addChild(rectangle);

Both rectangles just end up rendered relative to the stage. What am I doing wrong here?

Was it helpful?

Solution

You can add sprites as children to a sprite. But your problem is that you never changed the coordinates of your two sprites. So there is no visual difference that you can see because the stage and the parent sprite have the same coordinate system.

Try modifying the coordinates of the parent sprite and you will see the the child sprite moves with it.

Now to get a small rectangle inside a big one you can do like this:

public var rectangle:Sprite = new Sprite();
public var other:Sprite = new Sprite();

rectangle.graphics.beginFill(0xFF0000);
rectangle.graphics.drawRect(0, 0, 100, 100);
rectangle.graphics.endFill();

other.graphics.beginFill(0x00FF00);
other.graphics.drawRect(0, 0, 50, 50);
other.graphics.endFill();

rectangle.x = 250;
rectangle.y = 10;
other.x = 25;
other.y = 25;

rectangle.addChild(other);
this.addChild(rectangle);

OTHER TIPS

The problem is that when specifying coordinates to drawRect (or any other shape), no matter where it appears on the screen, the shape is always oriented at 0, 0. It's confusing and I'm not sure why it's set up that way, but the solution is always to draw your shapes at 0, 0 and then move them by specifying the x and the y. Then your child's x and y will be relative to the parent's.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top