World.allSprites

Category:Game Lab

Returns an array containing all the active sprites.

Sometimes you need to perform some actions on all the active sprites. Instead of coding multiples statements, one for each active sprite, you can use allSprites which creates an array, an indexed collection, of sprites that you can process one at a time with a loop.

Examples

Rotating Stickers

Use 26 different images for stickers, and randomNumber to place the stickers

                            //Rotating Stickers
var count = 0;

 for (var i = 0; i < 20; i++) {
  var sprite = createSprite(200, 200);
  sprite.setAnimation("sticker" + randomNumber(1,26));
  sprite.x = randomNumber(40, 360);
  sprite.y = randomNumber(40, 360);
}
var rotation = 0;
var turningRight = true;
var list = World.allSprites;

function draw() {
  background("white");
  if (rotation > 20) {
    turningRight = false;
  }
  
  if (rotation < -20) {
    turningRight = true;
  }
  
  if (turningRight) {
    rotation = rotation + 1;
  } else {
    rotation = rotation - 1;
  }
  
  for (var i = 0; i < list.length; i++) {
    list[i].rotation = rotation;
  }
 
  drawSprites();
}

                        

Syntax

World.allSprites

Returns

An array containing all the active sprites.

Tips

  • If you want to perform some action on a subset of active sprites create a Group instead of using allSprites.

Found a bug in the documentation? Let us know at documentation@code.org