Exit
  • Global community
    • Language:
      • Deutsch
      • English
      • Español
      • Français
      • Português
  • 日本語コミュニティ
  • 한국 커뮤니티
0

Adding child multiple times (HTML5 Canvas)

New Here ,
May 13, 2017 May 13, 2017

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.

1.6K
Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines

correct answers 1 Correct answer

LEGEND , May 13, 2017 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

Translate
LEGEND ,
May 13, 2017 May 13, 2017
LATEST

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

Translate
Report
Community guidelines
Be kind and respectful, give credit to the original source of content, and search for duplicates before posting. Learn more
community guidelines