Screen coords to world coords in a 2D scaled world.

Started by
1 comment, last by Zakwayda 5 years ago

Hi!

I need a way to convert screen coordinates obtained from mouse clicks to world coordinates in my 2D game.

To create a zoom effect controlled by the user, before drawing a model, I will scale all of it's points by a world scale value.

The screen origin (0,0) is at the top left corner while the world has it's center (0,0) at the center of the screen (screen width/2, screen height/2).

I need a function to convert the coords obtained by mouse clicks (screen coords) to the corresponding scaled-world coordinates, so that I can determine what world element is clicked by the user in this scaled world.

None of my approaches worked as required and unfortunately none of the found solutions where aplicable to my case.

This is a very simple example JS Bin: https://jsbin.com/rifutaboce/3/edit?html,output

Use the mouse wheel to zoom in/out Click on the screen to set a point

Thanks!

Advertisement

This:


function convert(coords) {
  const x = (-centerX + coords.x) / worldScale;
  const y = (-centerY + coords.y) / worldScale;
  return { x, y };
}

May get you closer. There still seems to be a slight inaccuracy proportional to the magnitude of the original click coordinates, but I'd have to spend more time with it to track down the cause of that.

The above solution is ad hoc. I think ideally you may eventually want something more formalized and consistent where the scale (and not just the position offset) is expressed via the canvas transform system, and input coordinates are adjusted via generalized inverse transform or coordinate mapping. I don't know what your goals are though, so maybe what you have now will be sufficient.

[Edit: As an aside, in modern JavaScript you can just write e.g. '{ x, y }' rather than '{ x: x, y: y }'.]

This topic is closed to new replies.

Advertisement