Kaboom.js; How to check if there is a collision when a key is pressed

339 Views Asked by At

The answer seemed simple at first, but it didn't work.
Here's what I did:

import kaboom from "kaboom";

kaboom();

loadSprite("bean", "sprites/bean.png");

const player = add([
    sprite("bean"),
    pos(80, height() / 2),
    area(),
        "Player",
]);

function spawnRect() {
        add([
            rect(50, 50),
            pos(width(), height() / 2),
            outline(4),
            area(),
            solid(),
            color(127, 200, 255),
                move(LEFT, 500),
                cleanup(),
                "Rect",
        ])
        wait(rand(0.25, 1.5), () => {
        spawnNote();
    });
}

spawnNote();

onKeyPress("d", () => {
        onCollide("Player", "Note", () => {
                shake();
        });
});

This didn't work but instead when I pressed "d", it continually checked if "Player" and "Note" was colliding. I only want it to check when I press "d". How do I do that?

1

There are 1 best solutions below

0
torusJKL On

I don't think you can check two concurrent events like this.

Instead use a condition to check if the key is pressed when the collision event is triggered.

onCollide("Player", "Note", () => {
  if (isKeyPressed("d")) {
    shake(120);
  }
});

Alternatively you can use a collision condition when the key is pressed but you would need the note object.

onKeyPress("d", () => {
  if (player.isColliding(note)) () => {
    shake(120)  
  }
})