Skip to main content
Participant
May 13, 2017
Answered

Adding child multiple times (HTML5 Canvas)

  • May 13, 2017
  • 1 reply
  • 1592 views

I'm developing a basic tank-shooter game in Animate CC. I have code similar to the following:

var missile = new lib.missile();

function fireMissile(){

     //adds missile to stage from library

     stage.addChild(missile);

     //sets missile to position and direction of tank, speed is set to 20    

      missile.x = tank.x;

      missile.y = tank.y;

      missile.dir = tank.dir;

      missile.speed = 20;

}

This code sets a missile (movie clip from the library) to the position of a tank and "fires" it by setting the speed to 20. The function is executed every time a user presses 'Enter'. The function works as intended, however, when the user presses 'Enter' multiple times the missile to set back to the position of the tank due to only one missile instance being on the stage.

My question is, is it possible to add a new child (the missile) according to each time the user presses 'Enter'? So this way it would recreate the missile instance every time the fireMissile function is called instead of reusing the same missile and interrupting its trajectory after being fired.

Thanks.

    This topic has been closed for replies.
    Correct answer ClayUUID

    The problem is literally your first line of code:

    var missile = new lib.missile();

    "Missile", singular. You're only instantiating a single missile object. addChild() doesn't instantiate, it just assigns ownership, which is why fireMissile() keeps resetting the same object.

    To solve this problem you'll have to create and manage an object pool of missile instances.

    Object Pool · Optimization Patterns · Game Programming Patterns

    1 reply

    ClayUUIDCorrect answer
    Legend
    May 13, 2017

    The problem is literally your first line of code:

    var missile = new lib.missile();

    "Missile", singular. You're only instantiating a single missile object. addChild() doesn't instantiate, it just assigns ownership, which is why fireMissile() keeps resetting the same object.

    To solve this problem you'll have to create and manage an object pool of missile instances.

    Object Pool · Optimization Patterns · Game Programming Patterns