Mouse/Touch Position to World Position

Oct 28, 2010 at 3:52 PM

I just wanted to let everyone know how to convert from Screen coordinates to a World position in your game.

Vector3 temp = GraphicsDevice.Viewport.Unproject(new Vector3(x, y, 0), _projection, _view, Matrix.Identity);

You simply Unproject the coordinates. The Z coordinate is irrelevant in an orthographic projection.

Typically _projection would be set to something like this -

Matrix.CreateOrthographic(float width, float height, float zNearPlane, float zFarPlane);

And _view is the translation and rotation matrix to change the offset and angle of your world.

Also to change from World coordinates to Screen you simply use Project instead of Unproject.

You should always include both of these methods somewhere in your game that is accessible everywhere.

Nov 15, 2010 at 4:07 PM

I'm having trouble getting this to work properly. I'm trying to turn mouse coordinates into World coordinates:

m_scr.X = mouseState.X;
m_scr.Y = mouseState.Y;

Vector3 temp = graphicsDevice.Viewport.Unproject(new Vector3(m_scr.X, m_scr.Y, 0), _camera.Projection, _camera.Transform, Matrix.Identity);

m.X = temp.X;
m.Y = temp.Y;

These are my camera's Projection and Transformation matrices:


Projection =
                Matrix.CreateOrthographic(zoom * graphicsDevice.Viewport.AspectRatio, zoom, 0, 1);

View =
              Matrix.CreateTranslation(-currentPosition.X, -currentPosition.Y, 0)
              * Matrix.CreateRotationZ(rotation);

Transform =
                * Matrix.CreateScale(graphicsDevice.Viewport.Height / zoom )
                * Matrix.CreateScale(1, -1, 1)
                * Matrix.CreateTranslation(graphicsDevice.Viewport.Width * 0.5f, graphicsDevice.Viewport.Height * 0.5f, 0f);

From what I gather, the code should unproject screen coords to World coordinates by metre, no? Any help would be much appreciated :)

Nov 15, 2010 at 6:57 PM
  1.  Either scale your projection matrix or your view matrix not both.
  2. Your view matrix should be rotated then translated.
  3. All that Transform stuff looks weird I would get rid of it.