Search code examples
actionscript-3collision-detectionhittest

Test the value of an array against hitTest object


Okay, I have an array in my Main Class that looks like this:

objectArray:Array = [ ];

I have three functions that create different items such as coins, enemies, hearts etc. Each of these added items are pushed into the objectArray. I am trying to write this function that hittests my bullets against any of these objects:

private function checkCollisions() :void{
    var bullet:MovieClip;
    for (var j:int = 0; j < objectArray.length; j++){
        object = objectArray[j];
        for(var i:int = 0; i < bulletArray.length; i++){
            bullet = bulletArray[i];
            if (objectArray[j].hitTestPoint(bullet.x, bullet.y, true)) {
                container.removeChild(bullet);
                bulletArray.splice(i,1);

                if (objectArray[j] == Enemy[j]){
                    container.removeChild(objectArray[j]);
                    objectArray.splice(j,1);
                    trace("enemy hit");
                }
            }
        }
    }
}

The problem is coming from this part:

if (objectArray[j] == Enemy[j]){  \\problem
    container.removeChild(objectArray[j]);
    objectArray.splice(j,1);
    trace("enemy hit");
}

I keep trying to figure a way to test the object that is being Hittested against a certain value such as "Enemy" so that I can produce different results based on what kind of object is being hit. No matter what combination of tests I try, I can't seem to get it to respond. When I trace objectArray[j], it produces [object Enemy] as a result. Is there a different way of testing Array values?


Solution

  • It sounds like you want to test if the object in objectArray[j] is an Enemy object. You can do this with the is operator:

    if (objectArray[j] is Enemy)
    {
        container.removeChild(objectArray[j]);
        trace ("enemy hit");
    }
    

    Edit

    Also, you might want to iterate over the bullet/object array's in reverse order, since you are potentially deleting entries from the array as you iterate over it.

    for (var j:int = objectArray.length -1; j >= 0; j--){
     // then do the same with the bullet array