How to make projectile shoot while camera is follow

Hi there,

I’ve been working on making a top down shooter, and I have a player, a tilemap, and am also able to shoot projectiles. If I dont use the camera, the aiming of each shot works perfectly. If I want to utilize the camera and make it follow the player, the activePointer that I’m using does not work how I want it to. The initial position of each projectile starts from the players position, and that works fine too.

let map = null;
let player,
  playerGroup = null;
let keys = null;
let lastFired = 0;
let isMouseDown = false;

function create() {
  // create keys
  keys = this.input.keyboard.addKeys("W,S,D,A");
  // camera zoom out
  this.cameras.main.setZoom(0.5, 0.5);
  // create map
  map = this.make.tilemap({
    key: "tilemap",
    tileWidth: 64,
    tileHeight: 64
  });
  // add tileset and layer
  let tileset = map.addTilesetImage("tiles");
  let collisionLayer = map.createStaticLayer(0, tileset, 0, 0);
  map.setCollision(0, true);
  // create player
  player = this.add.sprite(0, 0, "");
  // initialize weapon
  this.Bullet = new Phaser.Class(initBulletClass);
  this.bullets = this.add.group({
    classType: this.Bullet,
    maxSize: 30,
    runChildUpdate: true
  });
  // init camera to follow player
  // looks fine while camera is stationary
  // once camera follows, the activePointer starts to act wonky

  this.cameras.main.startFollow(player, true, 0.08, 0.08);
}

function update(time) {
  // create pointer
  let pointer = this.input.activePointer;
  // handle input and move player
  if (keys.A.isDown) {
    player.setAngle(-90);
    player.x -= 2.5;
  } else if (keys.D.isDown) {
    player.setAngle(90);
    player.x += 2.5;
  }
  if (keys.W.isDown) {
    player.y -= 2.5;
  } else if (keys.S.isDown) {
    player.y += 2.5;
  }

  // handle weapon update
  this.input.on("pointerdown", () => {
    isMouseDown = true;
  });

  this.input.on("pointerup", () => {
    isMouseDown = false;
  });

  if (isMouseDown == true && time > lastFired) {
    let bullet = this.bullets.get();
    if (bullet) {
      bullet.fire(player.x, player.y, pointer);
      bullet.setScale(1, 1);
      lastFired = time + 100;
    }
  }
}

I dont understand what I should be doing to prevent this from happening. Ideally, I should be able to shoot in the direction I choose, while the camera is following.

Here is the problem in codePen here.

Move:WSAD
Point and shoot with the mouse

Any help would be much appreciated.

in update change:
let pointer = this.input.activePointer;
to
let pointer = this.input.activePointer.positionToCamera(this.cameras.main);

and it should work as you want?

1 Like

Oh thanks a lot! It works perfectly. :slight_smile: