One feature of the GameScreen is that it can draw components in whatever order they want to be drawn in. This can be useful for features like transparency, where transparent objects must be drawn last so that they can draw over the object behind them. To implement this, we will provide a property on the Component class that will tell its parent at what point in the draw call it would like to be drawn. This will simply be an integer, and higher numbers will be drawn later. To start with, we will add this property to the Component class. You will note that in it’s “set” accessor it tells its parent to update the draw order.

int drawOrder = 0;

public int DrawOrder
{
    get { return drawOrder; }
    set
    {
        this.drawOrder = value;

        if (Parent != null)
            Parent.PutComponentInOrder(this);
    }
}

We now need to add the PutComponentInOrder function to the GameScreen. For efficiency reasons and for simplicity, the Components in the list are actually stored in their draw order. When that order changes, we must move the component whose draw order changed to its new position. This way, when drawing, as we are iterating throught he list, we will draw the components in order.

// The components are stored in their draw order, so it is easy to loop
// through them and draw them in the correct order without having to sort
// them every time they are drawn
public void PutComponentInOrder(Component component)
{
    if (components.Contains(component))
    {
        components.Remove(component);

        int i = 0;

        // Iterate through the components in order until we find one with
        // a higher or equal draw order, and insert the component at that
        // position.
        for (i = 0; i < components.Count; i++)
            if (components[i].DrawOrder >= component.DrawOrder)
                break;

        components.Insert(i, component);
    }
}

The last thing we want to do here is make sure that the list is sorted when a new component is added, so we will call PutComponentInOrder in the AddComponent method.

public void AddComponent(Component Component)
{
    if (!components.Contains(Component))
    {
        components.Add(Component);
        Component.Parent = this;
        PutComponentInOrder(Component);
    }
}

Download the Code for this Chapter

« »