0

I use the following code to set position of a DisplayObject to center.

obj.x = (screen_width - obj.width) / 2;

or

obj.x = (parentObj.width - obj.width) / 2;


And I use the following code to show 2 objects vertically.

obj2.x = obj1.width + interval


And I use the following code to show 2 objects vertically and set the position of them to center.

var obj3:Sprite = new Sprite;

obj3.addChild(obj1);
obj3.addChild(obj2);

obj2.x = obj1.width + interval;
obj3.x (screen_width - obj3.width) / 2;


Are the above codes a good way to manage positions of DisplayObjects?
Are there better and simple ways to do that?

Benny
  • 2,250
  • 4
  • 26
  • 39
js_
  • 4,671
  • 6
  • 44
  • 61
  • if you're not using flex, then they're spot on – divillysausages Sep 02 '11 at 08:21
  • @divillysausages I'm using free Flex SDK and just text editor. And I compile actionscript in command line. Do you mean that the codes in my question are the only choice for me? – js_ Sep 02 '11 at 09:03
  • 1
    no, you can still use flex using your setup (using mxml, or the flex components like HGroup or VGroup). those components provide a way to automatically layout objects inside them. If you're just using pure AS3 (which I think you are), then you do all this by hand, which is what you're doing and is fine – divillysausages Sep 02 '11 at 10:04

2 Answers2

1

Well you can also add them into a HGroup or a VGroup, (or HBox and VBox if you are using Flex 3). But when I want to implement a vertical layout without using these kind of elaborate objects, I usually create a "update()" method (note that the following code may contain syntax errors : it is just provided as an algorithm example):

private function update():void
{
    // The vertical gap between elements
    var gap:int = 4;

    // The cumuled height
    var cumuledHeight:Number = 0;

    // The number of elements
    var n:int = numElements;

    // The element at each loop
    var o:IVisualElement;
    for (var i:int = 0; i<n; i++) {

        // Gets the element
        o = getElementAt(i);

        // Sets its vertical position
        o.y = cumuledHeight + gap*i;

        // Updates the cumuled height
        cumuledHeight += o.height;
    }
}
LoremIpsum
  • 4,328
  • 1
  • 15
  • 17
1

Yes, there is a simpler way by using Flex to center it with horizontalCenter=0 and verticalCenter=0.

J_A_X
  • 12,857
  • 1
  • 25
  • 31
  • Thanks for your answer! But I think Sprite or DisplayObject doesn't have property called horizontalCenter and verticalCenter. – js_ Sep 06 '11 at 05:52
  • Is this pure AS or Flex? If it's flex, you can use FlexSprite instead. – J_A_X Sep 06 '11 at 06:27
  • Thanks for your reply. Actually I don't know what pure AS is and what Flex is. But I think I use pure AS because I'm using only actionscript and text editor and compiling a `.as file` in command line with Flex SDK. – js_ Sep 06 '11 at 07:55