PDA

View Full Version : Coordinate Systems


stage.Resize
11-05-2007, 03:29 PM
I'm having an issue resolving the correct dimensions for the stage. Check out this code below:

var brick1:Sprite = new Sprite();
var brickHolder:Sprite = new Sprite();
stage.addChild(brickHolder);
brickHolder.addChild(brick1);

brickHolder.x =0;
brickHolder.y = 0;
brickHolder.graphics.beginFill(0x00ffff);
brickHolder.graphics.drawRect(brickHolder.x, brickHolder.y, stage.stageWidth, stage.stageHeight);
brickHolder.graphics.endFill();

brick1.x = brickHolder.width/2-10;
brick1.y = brickHolder.height/2-10;
brick1.graphics.beginFill(0x000000);
brick1.graphics.drawRect(brick1.x, brick1.y, 20, 20);
trace("This brick is at: "+brick1.x+" "+ brick1.y);
trace("Stage size: "+stage.stageWidth + " " +stage.stageHeight);
brick1.graphics.endFill();

Now, what I expected to happen was there would be a square in the center of the viewable area right? But instead the square appears in the bottom right corner. If I don't divide by 2, the square appears waaaaay off screen. What gives? :confused:

jefgibso
11-05-2007, 04:35 PM
Have you tried simply using:

Stage.width and Stage.height

stage.Resize
11-05-2007, 04:47 PM
Thanks for the post,

Well the issue there is you can't just say Stage.x, the stage can only beaccesed through an DisplayObject. Also, if you just do:

brickHolder.graphics.drawRect(brickHolder.x, brickHolder.y, stage.width, stage.height);

Nothing will be draw because stage.width and stage.height are 0, I think because they have been superseded by stageWidth and stageHeight.

ryryguy
11-05-2007, 05:52 PM
The problem is that you are drawing the rect inside brick1 with a big offset. Basically, the drawing has a double offset: brick1's own x,y properties, then the graphic also has an offset of half the height and width of the stage.

This will get you the desired result:
brick1.graphics.drawRect(0, 0, 20, 20);

stage.Resize
11-05-2007, 07:05 PM
Oh I see it now. Thank you sir! Or Ma'am! :p

So the coordinate system of the brick1 is relative. I was assuming it was absolute with regard to the viewable area. The origin (0,0) of the brick1 is equal to the origin of it's parent container. Duh... so I was applying the extra offset... silly...

ryryguy
11-05-2007, 07:13 PM
Right, each display object's coordinate system is relative to its parent. It really helps keep things saner when you have some deep nesting going on.

There are some methods for converting around between coordinate systems if you need them. See DisplayObject.getRect, getBounds, globalToLocal, localToGlobal.