Calculating the Position of a Game Object Relative to the Camera in Phaser 3

While working on Keridwen, an accessible JavaScript puzzle game, I needed to get the absolute position of a game object in Phaser 3. That is, I had a large scrolling scene and I needed to know where the game object was drawn relative to the top-left corner of the canvas.

Looking through the Phaser docs I couldn't find an API that would give me that information, so I decided to try to calculate the position myself. After a few hours of trail and error I was finally able to to do it.

My initial attempts at calculating the position involved trying to use the main cameras scroll position to offset the objects world position. However, that didn't work out and it became super complicated trying to take into account when the camera stopped moving at the edges of the world.

I finally just looked at all the camera properties and stumbled upon the worldView property. This property is the current world rectangle that the camera is viewing. Importantly, the x and y position defines the top-left corner of the canvas.

Using this, all we have to do is subtract the game objects world position by the cameras world view position and we have the game objects position relative to the top-left corner of the screen. If your camera is zoomed we'll also need to multiply the final result by the camera zoom.

function getRelativePositionToCanvas(gameObject, camera) {
  return {
    x: (gameObject.x - camera.worldView.x) * camera.zoom,
    y: (gameObject.y - camera.worldView.y) * camera.zoom
  }
}