- XNA 4.0 Game Development by Example Beginner's Guide(Visual Basic Edition)
- Kurt Jaegers
- 355字
- 2021-08-20 15:50:38
Time for action – GamePiece class methods – part 4 – GetSourceRect
- Add the
GetSourceRect()
method to theGamePiece
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: