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

Time for action – GamePiece class methods – part 4 – GetSourceRect

  1. Add the GetSourceRect() method to the GamePiece class:
      public Rectangle GetSourceRect()
      {
          int x = textureOffsetX;
          int y = textureOffsetY;
            
          if (pieceSuffix.Contains("W"))
              x += PieceWidth + texturePaddingX;
    
          y += (Array.IndexOf(PieceTypes, pieceType) * 
               (PieceHeight + texturePaddingY));
    
    
          return new Rectangle(x, y, PieceWidth, PieceHeight);
      }

What just happened?

Initially, the x and y variables are set to the textureOffsets that are listed in the GamePiece class declaration. This means they will both start with a value of one.

Because the sprite sheet is organized with a single type of pipe on each row, the x coordinate of the Rectangle is the easiest to determine. If the pieceSuffix variable does not contain a W (signifying that the piece is filled with water), the x coordinate will simply remain 1.

If the pieceSuffix does contain the letter W (indicating the pipe is filled), the width of a piece (40 pixels), along with the padding between the pieces (1 pixel), are added to the x coordinate of the source Rectangle. This shifts the x coordinate from 1 to a value of 1 + 40 + 1, or 42 which corresponds to the second column of images on the sprite sheet.

To determine the y coordinate for the source rectangle, Array.IndexOf(PieceTypes, pieceType) is used to locate the pieceType within the PieceTypes array. The index that is returned represents the position of the tile on the sprite sheet (because the array is organized in the same order as the pieces on the image). For example, Left,Right returns zero, while Top,Bottom returns one and Empty returns six.

The value of this index is multiplied by the height of a game piece plus the padding between pieces. For our sprite sheet, an index of 2 (the Left,Top piece) would be multiplied by 41 (PieceHeight of 40 plus texturePaddingY of 1) resulting in a value of 82 being added to the y variable.

Finally, the new Rectangle is returned, comprised of the calculated x and y coordinates and the predefined width and height of a piece:

What just happened?