Question

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...

Was it helpful?

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 .

OTHER TIPS

There are several approaches to such a problem. One I like the most is to make a manager class that will contain all the objects in it, either as children or other structures, arrays etc. Then, your class you want to be aware of other instances is given a link to manager class (or gets it as this.parent, but this is more prone to errors), and calls its interface to get whatever info you need. For example, a Tower class that shoots monsters, requests manager class to get monsters within its range in order to choose a target, or your Enemy class searching for the player.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top