group.collide()

Category:Groups

Makes each sprite in the group stop when it runs into the target. If the target is moving, it will push the sprite with it. The target keeps moving as before.

Most games will involve sprites colliding with each other. There are four types of collisions available in Game Lab: bounce, bounceOff, collide and displace. These blocks will cause a certain type of interaction between each sprite and its target and must be used within the draw function.

Examples

Downpour

The umbrella stops a downpour.

                            // The umbrella stops a downpour.
var umbrella = createSprite(200, 200);
umbrella.setAnimation("umbrella");
umbrella.setCollider("circle", 0, 10);
var group = createGroup();
for (var i = 0; i < 100; i++) {
  var sprite = createSprite(randomNumber(0, 400), randomNumber(0, 100), 10, 10);
  sprite.setAnimation("raindrop");
  sprite.scale=0.05;
  group.add(sprite);
}
group.setVelocityEach(0, 10);
function draw() {
  background("white");
  group.collide(umbrella);
  drawSprites();
}

                        

Syntax

group.collide(target)

Parameters

NameTypeRequired?Description
target Sprite or Group The name of the target sprite or target group you want to check for a collision.

Returns

Boolean true or false. Changes output in the display after the sprites touch and drawSprites() is called.

Tips

  • All four of the collisions are similar to including an "if (sprite.isTouching(target))" in the draw function, and then depending on the collision type, updating the sprite and target velocityX and velocityY properties.
  • Only one of the four types of collisions should be specified for each pair of sprites.
  • To fine tune your collision detection use setCollider to change the shape and size of the collider area and set debug to true for the sprites.
  • A sprite that is not visible can still collide with other sprites and user mouse interactions.

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