Home > Enterprise >  hitTestObject is not working in actionscript class
hitTestObject is not working in actionscript class

Time:05-31

I am trying to test if the bullet defined in the .as file is touching the player defined in the .fla file.

I have this if statement in my .fla file

if (spaceBarPressed == true) {
    var eb = new EnemyBullet(player)
    stage.addChild(eb)
    eb.x = enemy.x   120
    eb.y = enemy.y   120
}

and this in my .as file

public function EnemyBullet(player) {
    addEventListener(Event.ENTER_FRAME, update)
    if (this.hitTestObject(player)) {
        trace("hit")
    }
}
function update(event:Event) {
    this.x =5
}

But I can't seem to get it to work.

CodePudding user response:

I fixed it by sending the object player to the function EnemyBullet in the class, and stored it in a variable of type DisplayObject to reference it in the function update.

Contents of if Statment in .fla file:

if (spaceBarPressed == true) {
    var eb = new EnemyBullet(player)
    stage.addChild(eb)
    eb.x = enemy.x   120
    eb.y = enemy.y   120
}

Contents of .as file

package  {
    
    import flash.display.MovieClip;
    import flash.display.DisplayObject;
    import flash.events.Event   
    
    public class EnemyBullet extends MovieClip {
        var $thing:DisplayObject
        
        public function EnemyBullet($testObject:DisplayObject) {
            $thing = $testObject
            addEventListener(Event.ENTER_FRAME, update)
        }
        function update(e:Event) {
            this.x =5
            if ($thing.hitTestObject(this) ) {
                trace("HIT")
            }
        }

    }
    
}
  • Related