Search code examples
actionscript-3collision-detectioncollision

AS3 Collision Detection Arrays


I've been trying to figure out an easier way to code this for a simple RPG I have been working on, it works perfectly if the item that is unable to pass through is added individually. When I've tried to work with arrays, it throws off a bunch of evil errors. Granted I am new to AS3 but I have tried to find a solution to this, with no luck.

if(heroMC.hitTestObject(block1)) {
    hitObj = true;
    heroMC.x = gX;
    heroMC.y = gY;
} else if(heroMC.hitTestObject(bridgeBlock2)) {
    hitObj = true;
    heroMC.x = gX;
    heroMC.y = gY;
} if(heroMC.hitTestObject(bridgeBlock3)) {
    hitObj = true;
    heroMC.x = gX;
    heroMC.y = gY;
} else {
    hitObj = false;
    gX = heroMC.x;
    gY = heroMC.y;
}

I then add every individual entry, to my list. If heroMC does intersect the object, then it changes the value of hitObj to true. If nothing is colliding, the hitObj will return as false. What solutions could I use to make this easier and cleaner.

Thanks in advance guys.


Solution

  • Insert your blocks MovieClips into an array

    var blocksArray: Arry = new Array(block1, bridgeBlock2, bridgeBlock3);
    

    Add Enter frame handler event for catch the changes

    this.addEventListener(Event.ENTER_FRAME, onEnterFramehandler);
    
     function onEnterFramehandler(e: Event): void {
            //initially set it to false
            hitObj = false;
            for (var i: uint = 0; i < blocksArray.length; i++) {
                //If  hit the object set it to true;
                if (heroMC.hitTestobject(blocksArray[i])) {
                    hitObj = true;
                    //set the position of the heroMc if true 
                    heroMC.x = gX;
                    heroMC.y = gY;
                    break;
                }
            }
            //get the position of the heroMc if false           
            gX = heroMC.x;
            gY = heroMC.y;
        }