Search code examples
actionscript-3flashactionscriptadobeflash-cs6

Redefining the hitbox of objects?


So, I've created a list of bullets and sharks, both these lists contain a defined amount of each object. Inside the shark movieclip I defined a hitbox by creating an movieclip called Hitbox, and given it an instance name "hitto"

When I test the collision with hitto and the bullet, it works but I get this random output error

TypeError: Error #2007: Parameter hitTestObject must be non-null.
    at flash.display::DisplayObject/_hitTest()
    at flash.display::DisplayObject/hitTestObject()
    at Missile/hitShark()

The collision test between the bullets and sharks

function hitShark(e:Event ):void {
    for each (bullet in bullets) {
        if (bullet.parent==null) {
            bullets.splice(bullets.indexOf(bullet),1);
        } else {

            for each (shark in sharks) {
                if (shark!=null&&bullet.hitTestObject(shark.hitto)) {
                    if (bullet.parent!=null) {
                        bullet.gotoAndPlay(2);
                        shark.health -= 1;
                        shark.gotoAndPlay(2);
                        //Removing while iterating over list causes errors;
                        bullets.splice(bullets.indexOf(bullet),1);
                        trace("HIT");
                    }
                }
            }
        }
    }
}

Ask me for some more clarification, I am new to as3 so my explanation might be confusing.

Screenshot to help possibly? http://prntscr.com/58u6ou


Solution

  • Well yeah flash does that, it needs some time to properly add movieclips to Stage. It's the reason why Event.ADDED_TO_STAGE exists, read this article to understand it better.

    But I'd say you would be pretty safe to go with a simple if statement making sure shark and shark.hitto are properly initialized and are sitting on stage.

    if(shark && shark.hitto) {
        // Do collisions
    }