views:

148

answers:

1

I have a 2d Camera with this translation matrix:

        Transform = Matrix.CreateTranslation(new Vector3(-Position.X, -Position.Y, 0)) *
                     Matrix.CreateRotationZ(Rotation) *
                     Matrix.CreateScale(new Vector3(Scale, Scale, 0)) *
                     Matrix.CreateTranslation(new Vector3((GraphicsDevice.Viewport.Width * 0.5f), (GraphicsDevice.Viewport.Height * 0.5f), 0));

Which works for Rotation/Zoom where the origin is the center of the camera.

Now I am trying to get the mouse coordinates in the world.

I tried just using an inverse transformation, but that just resulted in NaN errors. I am guessing I need to set up another translation matrix for the mouse coordinates, a reverse of the current one, but I can't figure out how this is set up

I have this,

MousePosition = new Vector2((Mouse.GetState().X - DrawTransform.Translation.X) * (1 / Gamecode.Camera1.Scale), (Mouse.GetState().Y - DrawTransform.Translation.Y) * (1 / Gamecode.Camera1.Scale));

But that doesn't take into account rotation

A: 

Generally it's easier and more robust to find the inverse of your matrix, than to calculate the client-to-world position by hand.

The problem with your matrix - the reason you cannot get the inverse, is that you're scaling the Z axis down to zero.

Matrix.CreateScale(new Vector3(Scale, Scale, 0))

This means that you've flattened your entire space on a single axis. So when you try to take a single point in that space (client space) and return it to the original space (world space) what you get back is actually a line stretching along the Z axis. This is why you get NaNs back. (Or you could just say - you've introduced a division by zero.)

The matrix inverse function doesn't know that you're just using a flat, 2D plane. XNA's matrices are 3D.

The fix is to change your matrix to this:

Matrix.CreateScale(Scale)

Then try finding the inverse.

Andrew Russell