as3居中对象

时间:2011-11-27 06:34:34

标签: actionscript-3 oop

好的,所以我有以下代码结构:

var environment:AvEnvironment = new AvEnvironment(stage.stageWidth, stage.stageHeight);   
addChild(environment);      
environment.addChild(new Player());
environment.addChild(new Terrain());

player类将xy上的信息传递给environment类,以便environment类以播放器对象为中心。由于terrain也是父项的子项,terrain类也将居中。但是,我不希望出现这种情况:我希望在创建游戏时,terrain类位于父级(environment)的左上角。

这是我尝试在terrain类中实现的代码:

if(parent)
            {
                var ev:AvEnvironment = AvEnvironment(parent);

                this.x = -ev.x
                this.y = -ev.y

            }

但是,这在构造函数方法中不起作用,因为父级返回null并且我不确定原因。

1 个答案:

答案 0 :(得分:0)

我认为你的Terrain在获得父级(addChild()之前)被初始化,调用上面的代码。您可以在Terrain类中尝试以下操作:

this.addEventListener(Event.ADDED_TO_STAGE, doDNATest); //Place this in your Terrain() constructor

function doDNATest(evt:Event) {
  //By the time this event is called you should know who the father is
  //since this is called once Terrain is on it's parent's (environment) display list
      if(this.parent)
      {
          var ev:AvEnvironment = AvEnvironment(this.parent);
          this.x = -ev.x
          this.y = -ev.y
      }
}