I'm developing a simple top-down game in Javascript using the 2d Canvas API. At the moment, I have the camera always centered on the player, such that they are always in the center of the screen. This is done like this:
let camX = -player.pos.x + this.canvas.width / 2;
tet camY = -player.pos.y + this.canvas.height / 2;
this.context.translate(camX, camY);
And it seems to work just fine. My issue comes in when I want to have the player click somewhere on the screen and have that click be translated into world coordinates. That is, if the player clicks somewhere, I should be able to use the relative mouse position combined with the camera transformation to obtain the world coordinates of the click.
I thought it would as simple as the following:
let worldX = -camX + input.mousePosition.x;
let worldY = -camY + input.mousePosition.y;
But it doesn't seem to be working. If I was using a normal camera object I would just take the inverse matrix I think, but this is just a simple canvas, so I'm not sure if I can do that in this case.
from How to convert from mouse coordinates to world coordinates in a Javascript canvas game?
No comments:
Post a Comment