Skip to main content
Known Participant
August 28, 2013
Answered

How to make a row of 5 objects to be in the center of the stage

  • August 28, 2013
  • 1 reply
  • 1004 views

Im trying to add 5 objects to the stage and the entire Row of the 5 objects to be centered on the stage. The objects will be with same Y position and a gap of 10px in between them.

the object have a center,center Registration poin

so far i have this, but it makes the 1st element go in the center and the rest follow him

for(var k:uint=0;k<5;k++){

                                        var gap = 10

                                var box:Box= new Box()

                                addChild(box);

                                box.x=stage.stageWidth/2 +  ( k*(gap+box.width));

}

This topic has been closed for replies.
Correct answer kglad

the easiest way without  prior knowledge of the objects' widths is to reposition them after initial positioning.  that could require looping through all the objects again but it's easier to just add the objects to a parent and center the parent:


var p:Sprite=new Sprite();

var gap = 10;

for(var k:uint=0;k<5;k++){                                                                       

var box:Box= new Box();

p.addChild(box);                                

box.x= k*(gap+box.width);

}

p.x=(stage.stageWidth-p.width)/2+box.width/2;

1 reply

kglad
Community Expert
kgladCommunity ExpertCorrect answer
Community Expert
August 28, 2013

the easiest way without  prior knowledge of the objects' widths is to reposition them after initial positioning.  that could require looping through all the objects again but it's easier to just add the objects to a parent and center the parent:


var p:Sprite=new Sprite();

var gap = 10;

for(var k:uint=0;k<5;k++){                                                                       

var box:Box= new Box();

p.addChild(box);                                

box.x= k*(gap+box.width);

}

p.x=(stage.stageWidth-p.width)/2+box.width/2;

Known Participant
August 28, 2013

Yeah i was thinking also of doing it with a parent Objectt and then setting the parent on the stage , but wanted to stay simple so i could directly modify every sigle Box , not by modifying parent.Box.

Cant i use the

var box:Box= new Box();

var boxWidth = box.width


and then somehow put the 1st element in the center and every other after him with a gap of 10

and then when there are 2 elements making thir 2x(combined width and gap) to be subtracted from the center,and so on for the rest of the 3 elements .

or in the end it will get even harder to manipulate them with this way im currently thinking ?? and do you recoment to stick with your code cause of simplicity for further modifications and adjustments (like if they move and if they are being hitted)

Known Participant
August 28, 2013

can you pls answer me so i would know what to do : ) 10x a lot for the support