Search code examples
javascriptkaboom

Colision on kaboom.js (javascript)


I'm trying to create a game where you have to collect coins to increase in size, but I can't detect when the player is touching the coin. I need to do this either with the Kaboom library or with pure JavaScript. This is my code:

import kaboom from "kaboom"

// initialize context
kaboom()

const speed = 150;
let PlayerScale = 1;

// load assets
loadSprite("player", "sprites/bean.png")
loadSprite("coin", "sprites/coin.png");

// Adicionar um sprite chamado "player"
const player = add([
  sprite("player"),
  pos(width() / 2, height() / 2),
  scale(PlayerScale),
  area(),
]);



// Adicionando um sprite chamado "coin"
const coin = add([
  sprite("coin"),
  pos(100, 100),
  scale(0.5), // scale the sprite down by half
]);

// Dale uma aumentada se tiver colidindo com a moeda. (That part is for colision)
player.onCollide("coin", () => {
    destroy(player)
})


// Mover o sprite com as teclas W, A, S e D
keyDown("w", () => {
  player.move(0, -speed);
});

keyDown("a", () => {
  player.move(-speed, 0);
});

keyDown("s", () => {
  player.move(0, speed);
});

keyDown("d", () => {
  player.move(speed, 0);
});

And yes, I have already looked at their documentation and have no idea what is happening.

(Sorry if english sucks)

I tried to use Kaboom.js collision with blocks:

// Dale uma aumentada se tiver colidindo com a moeda. (That part is for colision)
player.onCollide("coin", () => {
    destroy(coin)
    PlayerScale += 1
})
And this is the code for creating the sprites:

// Adicionar um sprite chamado "player" (create player)
const player = add([
  sprite("player"),
  pos(width() / 2, height() / 2),
  scale(PlayerScale),
  area(),
]);



// Adicionando um sprite chamado "coin" (create coin)
const coin = add([
  sprite("coin"),
  pos(100, 100),
  scale(0.5), // scale the sprite down by half
]);

I just want a system to scale the player when they touch the coin, and it can be done in JavaScript or using Kaboom.js please.


Solution

  • In order to use the onCollide method the target that you are trying to detect collision with must have two things, an area() component, and a tag matching the one you specify as the first argument to the onCollide function:

    const coin = add([
      sprite("coin"),
      pos(100, 100),
      scale(0.5), // scale the sprite down by half
      // this adds the Area component
      area(),
      // this adds the "coin" tag
      "coin"
    ]);
    

    Relevant documentation: