官术网_书友最值得收藏!

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

  1. Add the GetSourceRect() method to the GamePiece class:
    Public Function GetSourceRectangle() As Rectangle
      Dim x As Integer = textureOffsetX
      Dim y As Integer = textureOffsetY
    
      If _pieceSuffix.Contains("W") Then
        x += PieceWidth + texturePaddingX
      End If
    
      y += (Array.IndexOf(PieceTypes, _pieceType) *(PieceHeight + texturePaddingY))
    
      Return New Rectangle(x, y, PieceWidth, PieceHeight)
    End Function

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 1.

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 _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 a 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 0, while Top,Bottom returns 1, and Empty returns 6.

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 pre-defined width and height of a piece:

What just happened?
主站蜘蛛池模板: 陇西县| 公安县| 通州市| 大竹县| 广元市| 长治市| 冷水江市| 阿巴嘎旗| 太谷县| 彭州市| 木兰县| 纳雍县| 周至县| 延吉市| 灵台县| 萨嘎县| 鄂伦春自治旗| 尉氏县| 克山县| 南靖县| 辉县市| 柳州市| 清水河县| 新晃| 塔城市| 万荣县| 巧家县| 清涧县| 涟水县| 清镇市| 鸡西市| 固安县| 会泽县| 新巴尔虎右旗| 浦城县| 安庆市| 嘉黎县| 东方市| 吉木乃县| 富源县| 聂荣县|