Jump to content
  • Advertisement

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

Recommended Posts


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


Share this post

Link to post
Share on other sites
Posted (edited)


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 }'.]

Edited by Zakwayda

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!