group.setColliderEach()

Category:Groups

Sets the collider for every sprite in the group.

A collider is an invisible circle or rectangle that can have any size or position relative to the sprite and which will be used to detect collisions and overlapping with other sprites, or the mouse cursor.

If the sprite is checked for collision, bounce, overlapping or mouse events a rectangle collider is automatically created from the width and height parameter passed at the creation of the sprite or the from the image dimension in case of animated sprites.

Often the image default rectangle collider is not appropriate for collision detection so you can set a smaller circular or rectangular collider and offset from the sprite's center.

Examples

var group = createGroup();
for (var i = 0; i < 10; i++) {
  var sprite = createSprite(randomNumber(0, 400), randomNumber(0, 400),randomNumber(10, 20),randomNumber(10, 20));
  sprite.debug = true;
  group.add(sprite);
}
group.setAnimationEach("carrot_1");
group.setColliderEach("rectangle", 0, 0, 20, 80, -45);
function draw() {
  background("white");
  drawSprites();
}

Syntax

group.setColliderEach(type, xOffset, yOffset, width/radius, height, rotationOffset)

Parameters

Name Type Required? Description
type String The shape of the collider, "rectangle" or "circle".
xOffset Numebr The offset in the x-direction from the center of the sprite to the center of the collider. The default is 0.
yOffset Number The offset in the y-direction from the center of the sprite to the center of the collider. The default is 0.
width/radius Number The width of a rectangle collider or the radius of a circle collider. The default is determined by the size of the sprite.
height Number The height of a rectangle collider or the radius of a circle collider. The default is determined by the size of the sprite.
rotationOffset Number The clockwise rotation in degrees of the collider with respect to the sprite. The default is 0.

Returns

No return value. Determines sprite collisions and sprite-mouse interactions.

Tips

  • When your games have complex interactions between sprites or the mouse set sprite.debug to true so the sprite is shown with the outline of the collider, the depth, and center.
  • If setColliderEach() is called for a sprite before it is scaled, the collider is not scaled. But if a sprite is first scaled and then the collider set, the scale is also applied to the collider.
  • Groups of sprites all have the same functions and you use the dot notation (combining the name of the group, followed by a dot, with the function name) to call the function for that group of sprites.
  • Any changes to the properties of a sprite will not be seen until after drawSprites() is called.

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