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

Started by
-1 comments, last by homer_3 12 years, 4 months ago
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);

This topic is closed to new replies.

Advertisement