O'Reilly logo

Learning XNA 4.0 by Aaron Reed

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Layer Depth

You may have noticed that the second XNA logo is drawn overlapping the original logo. By default, XNA will draw each image on top of any previously drawn image, but there are some things you can do to affect the order in which images appear on the screen. The ordering of these overlapping images is referred to as the Z order, or the layer depth, of the images.

You may not care at this point which XNA logo is on top, but sometimes you’ll want a certain image to always be on top of other images. For example, in most games, you’ll typically want to show the moving characters on top of any background image. One way to do this is to make sure that whatever image you want on top is always drawn last. This method will work, but as the number of images you use in your game increases, organizing and staggering your Draw calls to achieve the desired results will become excruciatingly cumbersome.

Thankfully, XNA lets you specify a layer depth for each individual image, which allows you to always place images in the right Z order. To modify the layer depth, you need to convert both SpriteBatch.Draw method calls to the overloaded method used in the previous example. Convert your first Draw call to this overload as follows:

spriteBatch.Draw(texture,
    new Vector2(
    (Window.ClientBounds.Width / 2) - (texture.Width / 2),
    (Window.ClientBounds.Height / 2) - (texture.Height / 2)),
    null,
    Color.White,
    0,
    Vector2.Zero,
    1,
    SpriteEffects.None,
    0);

This code will draw your first sprite exactly the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required