Viewport Control

Have you ever wanted to make your game scroll and found that you have to do a lot of work to figure out where to draw your sprites on the screen? What about a zoom in/out? Or... what if you want to rotate your viewport? The Viewport class in Xen is meant to help you with this exact problem.

Using a Viewport

In a GameBase game class, you are already provided with a Viewport for each layer and the MainScene.Viewport allows you to control the MainScene's viewport.
In a non-GameBase game class, you will need to pass the Viewport's transformation when drawing your sprite.
Example of creating a Viewport and drawing sprites relative to the Viewport:
    public class GameMain : Game
    {
        IViewport2D _viewport = new Viewport2D(); // You can also do Viewport.Acquire();
        protected override void LoadContent()
        {
            _viewport.ResetWithScreenSize( 800, 480 );
            base.LoadContent();
        }
        protected override void Update( GameTime gameTime )
        {
            KeyboardState ks = Keyboard.GetState();

            #region Move Camera
            if( ks.IsKeyDown( Keys.A ) )
            {
                _viewport.MoveHorizontal( -5 );
            }
            if( ks.IsKeyDown( Keys.D ) )
            {
                _viewport.MoveHorizontal( 5 );
            }
            if( ks.IsKeyDown( Keys.W ) )
            {
                _viewport.MoveVertical( -5 );
            }
            if( ks.IsKeyDown( Keys.S ) )
            {
                _viewport.MoveVertical( 5 );
            }
            if( ks.IsKeyDown( Keys.Q ) )
            {
                _viewport.RotateBy( -0.04f );
            }
            if( ks.IsKeyDown( Keys.E ) )
            {
                _viewport.RotateBy( 0.04f );
            }
            if( ks.IsKeyDown( Keys.Z ) )
            {
                _viewport.ZoomIn( 1.04f );
            }
            if( ks.IsKeyDown( Keys.C ) )
            {
                _viewport.ZoomOut( 1.04f );
            }
            #endregion

            base.Update( gameTime );
        }
        protected override void Draw( GameTime gameTime )
        {
            GraphicsDevice.Clear( Color.CornflowerBlue );
            Matrix worldToCamera = _viewport.Transform.TranslateTo;
            _spriteBatch.Begin();
            foreach( var sprite in _sprites )
            {
                _spriteBatch.DrawSprite( sprite, worldToCamera );
            }
            _spriteBatch.End();
            base.Draw( gameTime );
        }
    }

Last edited Feb 7, 2011 at 1:10 AM by twohalf, version 1

Comments

No comments yet.