0
votes

I am writing code to have enemies detect collision with the player. In my Enemy class I have the following: import flash.display.MovieClip; import flash.events.Event;

public class Enemy extends MovieClip {
    var Player: MovieClip;
    public function Enemy() {
        this.addEventListener(Event.ENTER_FRAME, EnemyUpdate);

    }
    function setPlayer(_Player: MovieClip) {
        Player = _Player;
    }
    function EnemyUpdate(_event: Event) {
        var enemyHit: Boolean = this.hitTestObject(Player.Character.Legs);
        if (enemyHit) {
            trace("OUCH!!");
        }
    }

}

In my Main Class, I attempt to send the Player MovieClip to the Enemy Class script using the following:

    public function Main() {
        enemy.setPlayer(player);
    }

The MovieClip enemy has the Enemy script attached to it. When I run the program, the Player variable is null. How do I get the Player to recognize the Player MovieClip?

1

1 Answers

0
votes

This happens because you set your player after an Enemy had been instantiated. In Enemy constructor you have EnterFrame listener. To fix the error change your code as follows:

public function Enemy() {
    // empty constructor, you can remove it if there is no other logic in it

}
function setPlayer(_Player: MovieClip) {
    Player = _Player;
    // the Player variable is not null anymore. 
    this.addEventListener(Event.ENTER_FRAME, EnemyUpdate);
}