Search code examples
actionscript-3hittest

hitTest or hitTestObject to detect a collision with multiple objects in AS3?


I'm working on a small game and I would like to detect if the player collided with one of the boxes that are placed on the stage. What is the best method to do this, hitTest or hitTestObject? My code:

var hitTestClips:Array = [smallbox, mediumbox, bigbox] //more to come

    var fps = 60;
    var moveTimer:Timer = new Timer(1000/fps);

    moveTimer.addEventListener(TimerEvent.TIMER, onMoveTimer);
    moveTimer.start();

    function onMoveTimer(e:TimerEvent){
    player.x += Math.round(1)

    for(var player:MovieClip in hitTestClips)
    {
      if(player.hitTest(this.x, this.y, true))
      {
        trace("HIT");
      }
    }

    }

Solution

  • You can loop through the enemy objects and use hitTestObject to see if a collision occurred.

    var hasCollision:Boolean = player.hitTestObject( enemy );
    

    This page describes this and various other methods: AS3 Collision Detection