group.bounce()

Category:Groups

Makes the target bounce off each sprite in the group when they touch each other. Both the target and the sprite change how they are moving.

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

Bounce the Burger

Will the randomly moving parrots bounce the burger off the screen?

// Will the randomly moving parrots bounce the burger off the screen?
var target = createSprite(200, 200);
target.setAnimation("burger_1");
target.scale=0.25;
createEdgeSprites();
var group = createGroup();
for (var i = 0; i < 50; i++) {
  var sprite = createSprite(randomNumber(0, 400), randomNumber(0, 400), 10, 10);
  sprite.velocityY=randomNumber(-5, 5);
  sprite.velocityX=randomNumber(-5, 5);
  group.add(sprite);
}
group.setAnimationEach("parrot_1");
group.setScaleEach(0.1);
function draw() {
  background("white");
  drawSprites();
  group.bounce(target);
  group.bounceOff(topEdge);
  group.bounceOff(bottomEdge);
  group.bounceOff(leftEdge);
  group.bounceOff(rightEdge);  
}

Syntax

group.bounce(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