Search code examples
actionscript-3flashobjecthittestaddchild

Strange issues when using addChild and hitTest with AS3


I am having a couple of problems when adding a child in action script 3. I am currently building a Space Invaders game and I am writing the function that adds the asteroids to the stage.

My first problem is that the all previous asteroids are being added each time I try to add a new asteroid.

My second issue is when I add the hitTestOject function. It throws up an error and it doesn't do anything when the space ship hits the asteroid object.

Here is the error I receive with the hitTestObject:

TypeError: Error #1034: Type Coercion failed: cannot convert "ast_0" to flash.display.DisplayObject. at spaceranger_fla::MainTimeline/addAstroid() at flash.utils::Timer/_timerDispatch() at flash.utils::Timer/tick()

And here is my code. I use a timer so each asteroid is added every 5000ms:

// Add astoid
var astTimer:Timer = new Timer(5000);
astTimer.addEventListener(TimerEvent.TIMER, addAstroid);
var i:Number = 0;
function addAstroid (e:TimerEvent):void{
    var ast = new astroid();
    ast.name = "ast_"+i;
    ast.y = Math.random()*stage.stageHeight;
    ast.x = 565;
    addChild(ast);
    trace(i);
    if(ship.hitTestObject(ast.name)){
        gotoAndStop("2");
    }
i = i+1;
}

astTimer.start();

Some advice, recommendations and answers will be greatly appreciated :)

UPDATE

I sorted the looping error. Old asteroids no longer appear again! :D

Many Thanks,

Peter Stuart


Solution

  • Per your first problem, it does not appear i increments - it's always 0.

    When you assign name, increment i:

    ast.name = "ast_" + (i++).toString();
    

    Basically, saying i = i + 1;

    Next up, hit test against the instance itself, not an identity:

    ship.hitTestObject(ast)
    

    Not sure how your game play works, but it would seem what you really want are two handlers:

    • one to occasionally add a new asteroid
    • one that tests for collisions

    Currently your addAsteroid() function adds a new asteroid and immediately tests if it collides with the ship upon creation. That asteroid will never be tested for collision again. If this is similar to a classic asteroids game, you may want to push each asteroid to an array, and add an event listener for ENTER_FRAME to test each asteroid for collision against the ship.