Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

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?

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

1 Answer 1

up vote 1 down vote accepted

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.

share|improve this answer
    
You could use your _viewportWidth(Height) instead of Window.ClientBounds. –  dsilva.vinicius Oct 19 '13 at 1:02
    
Any particular advantage to one over the other? –  Gareth Oct 19 '13 at 15:59

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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