1

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');
     }
}

1 Answer 1

5

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).

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.