sprite.isTouching()

Category:Sprites

Checks if the sprite is touching the target sprite or any sprite in the target group.

All sprites have a collider area that defines the active area to detect collisions with other sprites and mouse interactions. Use setCollider to change the default collider area, a rectangle, for a sprite.

Examples

var sprite = createSprite(randomNumber(1, 400), randomNumber(1, 400));
var target = createSprite(randomNumber(1, 400), randomNumber(1, 400));
drawSprites();
if (sprite.isTouching(target)) {
  console.log("HIT");
} else {
  console.log("MISS");
}

Going for Gold

Will a randomly started sprite eventually touch a random static sprite?

                            // Will a randomly started sprite eventually touch a random static sprite?
var sprite = createSprite(randomNumber(1, 400), randomNumber(1, 400));
sprite.setAnimation("coin_silver_1");
var target = createSprite(randomNumber(1, 400), randomNumber(1, 400));
target.setAnimation("coin_silver_1");
sprite.setVelocity(randomNumber(-10, 10), randomNumber(-10, 10));
function draw() {
  background("white");
  drawSprites();
  if (sprite.x<0 || sprite.x>400) {
    sprite.velocityX=-1*sprite.velocityX;
  }
  if (sprite.y<0 || sprite.y>400) {
    sprite.velocityY=-1*sprite.velocityY;
  }
  if (sprite.isTouching(target)) {
    sprite.setAnimation("coin_gold_1");
  }
  else {
    sprite.setAnimation("coin_silver_1");
  }
}
                        

Syntax

sprite.isTouching(target)

Parameters

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

Returns

Boolean true or false.

Tips

  • 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.

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