XNA 4.0 Game Development by Example: Beginner's Guide
上QQ阅读APP看书,第一时间看更新

Time for action – fading pieces

  1. Add a new class to the Flood Control project called "FadingPiece".
  2. Add using Microsoft.Xna.Framework; to the using area at the top of the class.
  3. Update the declaration of the class to read class FadingPiece : GamePiece
  4. Add the following declarations to the FadingPiece class:
    public float alphaLevel = 1.0f;
    public static float alphaChangeRate = 0.02f;
  5. Add a constructor for the FadingPiece class:
    public FadingPiece(string pieceType, string suffix)
        : base(pieceType, suffix)
    {
    
    }
    
  6. Add a method to update the piece:
    public void UpdatePiece()
    {
        alphaLevel = MathHelper.Max(
            0, 
            alphaLevel - alphaChangeRate);
    }

What just happened?

The simplest of our animated pieces, the FadingPiece only requires an alpha value (which always starts at 1.0f, or fully opaque) and a rate of change. The FadingPiece constructor simply passes the parameters along to the base constructor.

When a FadingPiece is updated, alphaLevel is reduced by alphaChangeRate, making the piece more transparent.

Managing animated pieces

Now that we can create animated pieces, it will be the responsibility of the GameBoard class to keep track of them. In order to do that, we will define a Dictionary object for each type of piece.

A Dictionary is a collection object similar to a List, except that instead of being organized by an index number, a dictionary consists of a set of key and value pairs. In an array or a List, you might access an entity by referencing its index as in dataValues[2] = 12; With a Dictionary, the index is replaced with your desired key type. Most commonly this will be a string value. This way, you can do something like fruitColors["Apple"]="red";