动作脚本3.0。如何从另一个类访问MovieClip对象?

时间:2014-05-02 11:13:32

标签: actionscript-3 flash class actionscript movieclip

所以我有2个课程主要敌人。在Enemy类中,我需要使用在Main类中声明的变量。

这是我的主要类:

   public class Script extends MovieClip {
       var hero:MovieClip;
       var enemy:MovieClip; //These variables are only for example

       public function Game() {
                   hero.x = 100;
                   enemy.x = 200; // that's only example
   }
       function collisionDetected() {
                   enemy.hitBack(); // this is how I call hitBack function from Enemy class
   }

}

这是我的 Enemy 类:

public class Enemy extends MovieClip {
        private var count = 0;

        public function hitBack() {
            count = 0;
            this.addEventListener(Event.ENTER_FRAME, myEnterFrame);
        }

    private function myEnterFrame(e:Script)
    {
       if (count == 20) this.removeEventListener(Event.ENTER_FRAME, myEnterFrame);
       else 
       {
          count++;
          if (hero.x < enemy.x) { //here I need to use variables from Main class
            this.x -= 4;  
          }
           else {
            this.x += 4;  

          }
       }

    }

我遇到了错误

1120: Access of undefined property hero.
1120: Access of undefined property enemy.

1 个答案:

答案 0 :(得分:1)

您需要将该计算移至Main类,或者您也可以将变量传递给敌人类。由于你的例子被剥夺了,我不确定你的情况下什么是最好的,但我会倾向于将计算结果移出,假设你有多个敌人试图这样做。

public class Script extends MovieClip {
       var hero:MovieClip;
       var enemy:MovieClip; //These variables are only for example

       public function Game() {
                   hero.x = 100;
                   enemy.x = 200; // that's only example
                   this.addEventListener(Event.ENTER_FRAME, enterFrame);
       }

       function collisionDetected() {
                   enemy.hitBack(); // this is how I call hitBack function from Enemy class
       }

       function enterFrame(e:Event){
            theEnemyMovieclipClass.myEnterCheck(hero,enemy);
       }




public class Enemy extends MovieClip {
        private var count = 0;

        public function hitBack() {
            count = 0;
        }

    public function myEnterCheck(hero,enemy)
    {
       if (count == 20) {
            // DO SOMETHING
       }
       else 
       {
          count++;
          if (hero.x < enemy.x) { //here I need to use variables from Main class
            this.x -= 4;  
          }
           else {
            this.x += 4;  

          }
       }

    }
}

这样,如果你有多个,你可以循环遍历所有这些并在onEnterFrame上调用相同的方法。