KaboomJS: How to get the angle of the mouse in relation to a player/object.

Photo by Artem Bryzgalov on Unsplash

KaboomJS: How to get the angle of the mouse in relation to a player/object.

Jordi Enric's photo
Jordi Enric
·Oct 6, 2022·

1 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

I've been building a top-down shooter in Kaboom and had to figure out how to shoot bullets from the main player, here is a quick function to calculate the angle of the mouse in degrees in relation to a player.


  const player = add([
    sprite("lenny"), 
    pos(111, 111),
    color(220, 220, 250),
    area(),
    solid(),
  ]);

onClick(() => {
    const playerP = player.pos;
    const mouseP = mousePos();

    const angle = Math.atan2(mouseP.y - playerP.y, mouseP.x - playerP.x);

    const angleInDeg = (angle * 180) / Math.PI;

    play("pew", { volume: 0.1 }); // Very important
    spawnBullet(playerP, angleInDeg);
  });

function spawnBullet(p: Vec2, mouseP: number) {
  const BULLET_SPEED = 600;

  const bullet = add([
    rect(5, 5),
    area(),
    pos(p.sub(-12, -12)),
    origin("center"),
    color(255, 0, 0),
    outline(1),
    move(mouseP, BULLET_SPEED),
    cleanup(),
    // strings here means a tag
    "bullet",
  ]);
}
 
Share this