Search code examples
actionscript-3flashclassobjectscene

How do I access an object on the scene from a public class Myclass extends MovieClip?


When I'm in the main code which is in the first frame of my scene, I can access the player.x and y propertie fine, but from the class Enemy.as I can only send the parameters once in the construction but I don't know how to update constantly those coordinate in the loop. xb and yb are the coordinate of my player object on the scene I sent as parameter for each time I create an Enemy object on my scene but this method only give the coordinate once. I'd like to update the coordinate of the player object at each loop, how do I do that ? I tried the line: trace("this.parent.player.x") but it don't work.

    public function Enemy(xLocation:int, yLocation:int, xb, yb) {
        // constructor code
        x = xLocation;
        y = yLocation;
        addEventListener(Event.ENTER_FRAME, loop);
        xa = xb;
        ya = yb;
    }

    public function loop(e:Event):void {

            x -= xSpeedConst;
            trace(this.x);
            trace (xa + " " + ya);

    }

Any help would be greatly appreciated...


Solution

  • Just pass in your player instance into the Enemy instead of the coordinates and then save the instance inside of the Enemy for example:

    public class Enemy{
      private var player:Player;
    
      public function Enemy(xLocation:int, yLocation:int, playerParam){
        player = playerParam;
      }
    }
    

    Now in your loop you should be able to access the player's updated x and y values by saying: player.x or player.y .