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.

While you may not care at this point which XNA logo is on top, 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 ...

Get Learning XNA 3.0 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.