• Advertisement
Sign in to follow this  

Getting world coords from screen in 2D XNA? [Solved]

This topic is 2263 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

I'm not sure how I can get the world coordinates of my mouse on the screen in a 2D XNA game. I'm using SpriteBatch to do my rendering, so there aren't really any matrices involved that I'm aware I have access to. I am using the overloaded SpriteBatch.Begin which lets me pass in a translation matrix, but that's the only matrix I'm aware of. So I think my world matrix is basically just the translation that I pass in to SpriteBatch.Begin. I'm currently trying



MouseState ms = Mouse.GetState();
Vector3 mPos = new Vector3(ms.X, ms.Y, 1);
mPos = graphics.GraphicsDevice.Viewport.Unproject(mPos, Matrix.Identity, Matrix.Identity, spriteBatchMatrix);


But this doesn't work. I'm hovering my mouse over a known coordinate and mPos isn't even remotely close. It also appears to be a normalized value.

Edit: I should have googled harder. I found the solution on stackoverflow.



MouseState ms = Mouse.GetState();
Vector3 mPos = new Vector3(ms.X, ms.Y, 100);
Matrix tMat = Matrix.Invert(spriteBatchMatrix); //spriteBatchMatrix is the translation matrix passed to SpriteBatch.Begin
mPos = Vector3.Transform(mPos, tMat);

Share this post


Link to post
Share on other sites
Advertisement
Sign in to follow this  

  • Advertisement