2D and 3D Combined

## Introduction

We have spent a lot of time in these tutorials learning how to do both 2D and 3D drwaing. One thing that we haven't discussed in earlier tutorials is a combination of the two. In 3D games, there is usually a significant 2D component in the form of menus, HUDs, and other things. In this tutorial, we will deal with a problem that arises when we try to combine 2D graphics with 3D.

## 2D and 3D Combined

In previous tutorials, we dealt with 3D coordinate systems. We used matrices to get everything the way we want it in 3D space. We've dealt with 3D coordinate systems before. It is just a simple matter of specifying at which pixel you want to draw images and text. But we run into a problem when we combine these two coordinate systems. It turns out, there's not really a good way for them to overlap. When we try doing the two in the ways that we've used up until this point, our 3D models usually don't get drawn correctly, like in the image below. In this picture, we can see the front of the ship, right through the back of the ship.

The basic problem is that in the 3D world, there's a depth buffer at work. The depth buffer is a way for the program to keep track of what triangles are in front of other triangles, on a pixel-by-pixel basis. The depth buffer is the mechanism that makes things look right, no matter what order the triangles of your model are drawn in. The depth buffer can be turned on or off pretty easily. But what's happening in this case, is when we go to draw in 2D, it shuts off the depth buffer, making our 3D stuff not look right.

The solution to this is actually very simple. All we need to do is turn the depth buffer back on before drawing in 3D again.

The following single line of code does this:

```GraphicsDevice.DepthStencilState = new DepthStencilState() { DepthBufferEnable = true };
```

Place this after any 2D drawing code, and before any 3D drawing code.

This simple change should result in the following:

## What's Next?

This tutorial went through a solution for a problem that arises when you use 2D and 3D drawing together. From here, I suggest you take a look at the rest of the 2D and 3D tutorials, if you haven't already. Otherwise, consider going on to the other advanced XNA tutorials.

 Having problems with this tutorial? Try the troubleshooting page!