0
\$\begingroup\$

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:

 _SpriteBatch.Begin( SpriteSortMode.FrontToBack, null, SamplerState.PointClamp, // Don't smooth null, null, null, _Camera.GetTransformation()); 

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?

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

1 Answer 1

1
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ You could use your _viewportWidth(Height) instead of Window.ClientBounds. \$\endgroup\$ Commented Oct 19, 2013 at 1:02
  • \$\begingroup\$ Any particular advantage to one over the other? \$\endgroup\$ Commented Oct 19, 2013 at 15:59

You must log in to answer this question.