var group = createGroup()

Category:Groups

Creates a new group and assigns it to the variable specified.

Groups are collections of sprites with similar behavior. For example a group may contain all the sprites in the background or all the "enemy" sprites. Instead of maintaining the images, animations, and properties (such as position, movement, and collisions) on each individual sprite, you can manage them on the group. A sprite can be in multiple groups and deleting a group doesn't affect the sprites themselves.

Examples

var group = createGroup();
group.add(createSprite(200, 200, 100, 100));
group.add(createSprite(200, 100, 50, 50));
group.setSpeedAndDirectionEach(randomNumber(-3, 3), randomNumber(-45, 45));
function draw() {
  background("white");
  drawSprites();
}

Swarm

Swarm of bees following the mouse.

// Swarm of bees following the mouse.
var group = createGroup();
for (var i = 0; i < 100; i++) {
  group.add(createSprite(randomNumber(150, 250), randomNumber(150, 250), 2, 2));
}
group.setAnimationEach("bee_1");
group.setScaleEach(0.5);
group.setRotateToDirectionEach(true);
function draw() {
  background("white");
  drawSprites();
  var direction=(180*Math.atan2(World.mouseY-200, World.mouseX-200))/Math.PI;
  group.setSpeedAndDirectionEach(10, direction);
}

Pig Catch

Catch the randomly falling pigs with the paddle.

// Catch the randomly falling pigs with the paddle.
var paddle = createSprite(200, 350, 100, 10);
createEdgeSprites();
var group = createGroup();
for (var i = 0; i < 20; i++) {
  var sprite = createSprite(randomNumber(0, 400), randomNumber(0, 100), 10, 10);
  sprite.velocityY=randomNumber(5, 10);
  sprite.velocityX=randomNumber(-5, 5);
  sprite.bounciness = randomNumber(0.5, 2);
  group.add(sprite);
}
group.setAnimationEach("pig_pink_1");
group.setScaleEach(0.1);
function draw() {
  background("white");
  drawSprites();
  if (keyDown("right")) {
    paddle.x = paddle.x+10;
  }
  if (keyDown("left")) {
    paddle.x = paddle.x-10;
  }  
  group.bounceOff(paddle);
  group.bounceOff(topEdge);
  group.bounceOff(leftEdge);
  group.bounceOff(rightEdge);  
}

Syntax

var group = createGroup()

Returns

Returns the sprite group and assigns it to the variable specified.

Tips

  • Change the image displayed for all the sprites in a group from the default rectangle using the setAnimationEach command. All images must be first loaded and given a label using the Animation tab above the display window in Game Lab.
  • All sprites in a group have the same properties and you use the dot notation (combining the name of the group, followed by a dot, with the label of the property) to both access and update the property for all the sprites in that group.
  • If you attempt to set a group property to an incorrect value the property reverts to its default value.

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