On a default Phaser project, I have a sprite positioned at 100, 100. I want to get its coordinates when zoomed in to place an absolute div on top of it in HTML.
On zoom 1 this works:
const viewportX = (spriteX - this.cameras.main.scrollX);
const viewportY = (spriteY - this.cameras.main.scrollY);
but as soon as I change the zoom it breaks, I've tried adding the cameras.main.zoom
, multiplying it, dividing it, and the coordinates are not the correct one.
I understand the documentation for the zoom mentions Changing the zoom does not impact the Camera viewport in any way, it is only applied during rendering.
So I'm at a loss as to how I can zoom in everything but still obtain a zoomed in sprite's coordinates.
An MRE of this would be creating a project with npm create @phaserjs/game@latest
with the following options:
√ Select Option: » Client Framework (React, Next.js, Vue, Angular, Svelte, SolidJS or Rapier)
√ Select Template: » solid
√ Minimal or Complete Project: » Minimal (Single Phaser Scene)
and only changing the create function to this:
create() {
this.cameras.main.centerOn(200, 200)
this.cameras.main.setZoom(5)
const logo = this.add.image(200, 200, 'logo');
EventBus.emit('current-scene-ready', this);
}
What I'm looking for in this case is the top left position of the sprite in viewport coordinates, in this case at default canvas width it'd be outside of the canvas, I'm looking for a way of getting where those coordinates are relative to my viewport, in this case if I fullscreen and set the canvas width to 1920 and height to 1080, then that top left position of the sprite would be somewhere in the negative x and positive y.
edit: A third example.
If I have this:
this.cameras.main.centerOn(200, 200)
this.cameras.main.setZoom(1)
const line = this.add.line(150, 150, 0, 0, 1, 1, 0xffffff, 1).setOrigin(0, 0);
console.log(line.x - this.cameras.main.scrollX, line.y - this.cameras.main.scrollY)
And i create an absolute positioned div with those logged coordinates, then it's on the bottom right of where the line ends, but if i set the zoom to 2 then it doesn't anymore. These new zoomed in coordinates are what I want.
I haven't figured it out but for all intents and purposes what worked for me was using Phasers Dom Element with Solid.js and that places what I want in the sprite's x and y coordinates and moves along with the canvas when the camera moves.