Collision Detection

Sometimes, you'll want to know when two sprites are touching each other. Game Lab uses the method isTouching to check whether one sprite is touching another sprite (the target).

isTouching returns a Boolean, so it can be used inside a conditional to cause something to happen only when the two sprites touch. For example, the code below changes the animation of the watermelon when the knife sprite touches it.

function draw() {
  if (knife.isTouching(watermelon)) {
    watermelon.setAnimation("slice");
  background("burlywood");
  drawSprites();
}

Colliders

When Game Lab checks whether two things are touching, it doesn't know what parts of the image are visible. Instead, it checks whether the colliders are touching each other. The size of the colliders is determined by the size of the animation that you are using, even the parts of it that you can't see. You can see the colliders by setting the sprite's debug property to true.

In the two examples to the right, debug has been set to true, so you can see the green outline of the colliders, and that the animation changes when they touch, even if the pictures of the knife and watermelon aren't touching each other.

In the second example, the colliders are very large, so the watermelon changes long before the knife touches it.

watermelon.debug = true;
knife.debug = true;

function draw() {
  if (knife.isTouching(watermelon)) {
    watermelon.setAnimation("slice");
  background("burlywood");
  drawSprites();
}

You can also change the shape of the colliders using the method setCollider. This method makes the collider a circle or a rectangle.

watermelon.debug = true;
knife.debug = true;
watermelon.setCollider("circle");
knife.setCollider("circle");

function draw() {
  if (knife.isTouching(watermelon)) {
    watermelon.setAnimation("slice");
  background("burlywood");
  drawSprites();
}

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