Zach
Zach

Reputation: 650

Killing all elements in a group(Phaser)

I have a clouds group that will spawn two clouds. Every 10 seconds I want to kill those clouds and spawn two more clouds. Can you kill all elements of a group at once?

var clouds;
var start = new Date();
var count = 0;

function preload(){
     game.load.image('cloud', 'assets/cloud.png');
}

function create(){
     clouds = game.add.group();
}

function update(){
     if(count < 10){
         createCloud();
     }
}

function createCloud(){
     var elapsed = new Date() - start;

     if(elapsed > 10000){
       var locationCount = 0;
       //Here is where I'm pretty sure I need to
       //kill all entities in the cloud group here before I make new clouds
       while(locationCount < 2){
             //for the example let's say I have a random number
             //between 1 and 3 stored in randomNumber
             placeCloud(randomNumber);
             locationCount++;
             count++;
        }
     }
}


function placeCloud(location){
     if(location == 1){
         var cloud = clouds.create(170.5, 200, 'cloud');
     }else if(location == 2){
         var cloud = clouds.create(511.5, 200, 'cloud');
     }else{
         var cloud = clouds.create(852.5, 200, 'cloud');
     }
}

Upvotes: 1

Views: 3503

Answers (1)

James Skemp
James Skemp

Reputation: 8571

You should be able to do one of the following to kill all the elements in a group:

clouds.forEach(function (c) { c.kill(); });

forEach() documentation. Or perhaps better, forEachAlive().

clouds.callAll('kill');

callAll() documentation.

However, I wonder if you may want to look at using an object pool for this instead, as I believe that you may have garbage collection issues if you use your current method for an extended period of time.

The official Coding Tips 7 has some information on using pools (in their case for bullets).

Upvotes: 5

Related Questions