Export (0) Print
Expand All

How To: Use Viewports for Split Screen Gaming

This example demonstrates how to use the Viewport property to display different scenes to different parts of the screen.

This sample assumes there are two camera classes in use, Camera1 and Camera2.

The Complete Sample

The code in this tutorial illustrates the technique described in the text. A complete code sample for this tutorial is available for you to download, including full source code and any additional supporting files required by the sample.

To Create a Split Screen

  1. In your LoadContent method, create two new Viewport objects to define the two new "split" regions of the screen. In this example, the screen is split in half vertically.

    Viewport defaultViewport;
    Viewport leftViewport;
    Viewport rightViewport;
    Matrix projectionMatrix;
    Matrix halfprojectionMatrix;
    protected override void LoadContent()
    {
        // Create a new SpriteBatch, which can be used to draw textures.
        spriteBatch = new SpriteBatch(GraphicsDevice);
    
        defaultViewport = GraphicsDevice.Viewport;
        leftViewport = defaultViewport;
        rightViewport = defaultViewport;
        leftViewport.Width = leftViewport.Width / 2;
        rightViewport.Width = rightViewport.Width / 2;
        rightViewport.X = leftViewport.Width + 1;
    
  2. Immediately after creating the two new viewports, create a projection matrix to fit each new viewport. In this case, because the screen is split in half, only one new projection matrix is necessary. It has the same settings as the 4:3 full screen projection matrix, except the aspect ratio is now 2:3.

        projectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 4.0f / 3.0f, 1.0f, 10000f);
        halfprojectionMatrix = Matrix.CreatePerspectiveFieldOfView(MathHelper.PiOver4, 2.0f / 3.0f, 1.0f, 10000f);
    }
    
  3. In your Draw method, assign one of the viewports to draw as the GraphicsDevice Viewport. Then draw your scene as normal, using the camera (or view matrix) associated with this perspective, along with the proper projection matrix.

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Viewport = defaultViewport;
        GraphicsDevice.Clear(Color.CornflowerBlue);
    
        GraphicsDevice.Viewport = leftViewport;
        DrawScene(gameTime, Camera1.ViewMatrix, halfprojectionMatrix);
    
  4. After drawing the first scene, assign the other viewport to the Viewport property, and draw your scene again with the associated camera or view matrix, and the proper projection matrix.

        GraphicsDevice.Viewport = rightViewport;
        DrawScene(gameTime, Camera2.ViewMatrix, halfprojectionMatrix);
    
        base.Draw(gameTime);
    
    }
    

Community Additions

ADD
Show:
© 2014 Microsoft