Question

I am trying to make a game similar to the world's hardest game, but I have trouble with the hitTestObject block. This is my code for the enemy mi:

package  {

  import flash.display.MovieClip;
  import flash.events.Event;


public class enemys extends MovieClip {

public function enemys() {

    stage.addEventListener(Event.ENTER_FRAME, hittrue)

}

public function hittrue(event:Event) {

    if (this.hitTestObject(?)) {

        while (numChildren > 0) {

            removeChildAt(0)
            }

        gotoAndStop(2)

        }

    }   

}
}

I don't know what to put into the question mark. When I put the instance name of my player, it says that it is undefined.

Was it helpful?

Solution 2

How do you put the instance name of player? Do you pass the instance through the constructor?

From you main class you need to send a instance of your player to the enemys class. (by the way plural for enemy is enemies)

public class Enemies extends Sprite{

   private var player:PlayerClass;

public function Enemies(p:PlayerClass) {

   stage.addEventListener(Event.ENTER_FRAME, hittrue);
   player = p;
}

Then in you can put 'player' where the ? is. And in yout main class you would have something like:

var enemies:Enemies = new Enemies(player);

I changed MovieClip to Sprite. This is your choice but it is sometimes better to use Sprites because it will be faster then MovieClip. You may want to look into them especially if you are going to have multiple enemies on the stage at a time.

Another thing is the design of you ENTER_FRAME event.

You do not want multiple Enter_Frame events going on in multiple classes. A good design is to have one in your main class. Then from classes that need a clock cycle, call update methods on these objects in the main class's ENTER_FRAME event.

so in your main class's ENTER_FRAME event you would call:

enemies.hittrue();

Instead of having an EnterFrame event in you enemies class. This will also make it much easier to pause your game.

And as The other answer suggests. Your Collision detection should really be outside of your Enemies Class. But, this is how you would pass a reference of you player to another class.

OTHER TIPS

You're getting an error because enemys (sic) doesn't appear to have access to any sort of player instance.

You should move the hit testing out of the enemys class to somewhere you have access to both enemys and the instance of player. A good place for this would be some kind of GameEngine class.

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