I have a 2D tile based game in XNA, with a moveable camera that can scroll around and zoom.

I'm trying to obtain a rectangle which indicates the area, in world space, that my camera is looking at, so I can render anything this rectangle intersects with (currently, everything is rendered).

So, I'm drawing the world like this:

                SamplerState.PointClamp,        // Don't smooth            
                null, null, null,

The GetTransformation() method on my Camera object does this:

    public Matrix GetTransformation()
        _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;

The camera properties in the method above should be self explanatory.

How can I get a rectangle indicating what the camera is looking at in world space?

  • \$\begingroup\$ Do you use rotation? \$\endgroup\$ – Vaughan Hilts Oct 17 '13 at 17:56
  • \$\begingroup\$ No, camera has fixed rotation. \$\endgroup\$ – Gareth Oct 17 '13 at 17:58
  • \$\begingroup\$ You can just create one from the position of the rectangle then, viewport width and height, multiplied by scale. \$\endgroup\$ – Vaughan Hilts Oct 17 '13 at 17:59
  • \$\begingroup\$ Sorry, I don't understand that. Surely the camera position has to be involved? \$\endgroup\$ – Gareth Oct 17 '13 at 18:10
  • 1
    \$\begingroup\$ Sorry, by position of rectangle I meant the camera... :) \$\endgroup\$ – Vaughan Hilts Oct 17 '13 at 18:14

Ok, so here's what seemed to do the trick:

 Rectangle CameraWorldRect = new Rectangle(
                Convert.ToInt32(_Camera.Pos.X - ((Window.ClientBounds.Width / 2) / _Camera.Zoom)),
                Convert.ToInt32(_Camera.Pos.Y - ((Window.ClientBounds.Height / 2) / _Camera.Zoom)),
                Convert.ToInt32(Window.ClientBounds.Width / _Camera.Zoom),
                Convert.ToInt32(Window.ClientBounds.Height / _Camera.Zoom));

Reduced CPU usage 3% by not drawing unnecessary tiles, happy days.

  • \$\begingroup\$ You could use your _viewportWidth(Height) instead of Window.ClientBounds. \$\endgroup\$ – dsilva.vinicius Oct 19 '13 at 1:02
  • \$\begingroup\$ Any particular advantage to one over the other? \$\endgroup\$ – Gareth Oct 19 '13 at 15:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.