2D Avatars Using Render Targets (XNA Game Studio 4.0 Programming)

Although the avatars render in 3D, it is possible to use them within your 2D game easily. One method to do this is to draw the animating avatars to a render target and then use the texture from the render target as you would any other 2D texture in your game.You can even build sprite sheets from the avatar animations.

Let’s create a sample that shows how to render an avatar to a RenderTarget and then display the texture as a sprite. Start with the existing sample that displays a random avatar animation. For an additional member variable to store the RenderTarget, add the following member variable to your game’s class.

tmp14-177_thumb

To initialize the RenderTaget so it is ready to be set on the device, add the following to the LoadContent method in your game:

tmp14-178_thumb


You also want to change the projection matrix to use an aspect ratio of 1 because the width and height of the texture are equal.

tmp14-179_thumb

The last portion of code changes the way you render the avatar in the game’s Draw method. Update the game’s Draw method to contain the following code:

tmp14-180_thumb

First, set your render target and clear the render target to transparent.You clear to transparent to be able to composite the texture with other textures in your game. Then, draw the avatar as you would normally by setting the World, View, and Projection transforms before calling the Draw method. This draws the avatar to the render target.

The render target is then set to null to switch back to the backbuffer. The backbuffer is then cleared to CornflowerBlue before the SpriteBatch is used to draw the render target to the screen.

If you run the sample now, notice that the the texture with the avatar appears in the upper right-hand corner of the screen. Because the rest of the texture is transparent, it is difficult to tell you are using a render target.You can change the clear color when clearing the render target to show that you are in fact drawing the avatar to the screen using a texture that is created using a render target. Figure 10.12 shows the avatar drawn to the screen using a render target.

Avatar drawn to the screen using a render target

Figure 10.12 Avatar drawn to the screen using a render target

Next post:

Previous post: