4
\$\begingroup\$

I have a problem with a camera class I got from the internet. It does a transformation like this:

public Matrix get_transformation(GraphicsDevice graphicsDevice)
    {
        _transform =   
          Matrix.CreateTranslation(new Vector3(-_pos.X, -_pos.Y, 0)) *
                                     Matrix.CreateRotationZ(Rotation) *
                                     Matrix.CreateScale(new Vector3(Zoom, Zoom, 1)) *
                                     Matrix.CreateTranslation(new Vector3(ViewportWidth * 0.5f, ViewportHeight * 0.5f, 0));
        return _transform;
    }

Later the spritebatch is called like this:

spriteBatch.Begin(SpriteSortMode.BackToFront,
                    BlendState.AlphaBlend,
                    null,
                    null,
                    null,
                    null,
                    cam.get_transformation(device));

The problem is that at this point the mouse coordinates are not relative anymore to the other sprites I draw. This is a problem because I try detect which sprite has been clicked. I understand that this issue can be solved by considering the following picture:

enter image description here

This was posted in a very good awnser before, here. But somehow this does not really help me. So my question is:

Is there a way to create a Camera class which does not use transformation, can be moved with keys and keeps the viewport coordinates relative?

Thanks in advance!

\$\endgroup\$

1 Answer 1

5
\$\begingroup\$

A matrix simply applies some transformation on the coordinates of the object in order to send them to another coordinate system. In this case, the camera matrix converts world coordinates to screen coordinates. You can revert the process (that is, convert screen coordinates back to world coordinates) by transforming the screen coordinates with the inverse of the camera matrix.

Suppose mouseVector holds the coordinates of the mouse in screen space. Then the coordinates in the world will be:

worldMouse = Vector2.Transform(mouseVector, Matrix.Inverse(camera.getTransformation()));

Now that you have the world coordinates of the mouse, you can test for clicks on top of objects as usual.

\$\endgroup\$
1

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .