group.add()

Category:Groups

Add a sprite to the group.

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

Syntax

group.add(sprite)

Parameters

NameTypeRequired?Description
sprite Sprite The sprite to add to the group.

Returns

No return value.

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