- 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:

- 計算機組成原理與接口技術:基于MIPS架構實驗教程(第2版)
- 云數據中心基礎
- Python數據挖掘:入門、進階與實用案例分析
- 數據庫系統原理及應用教程(第4版)
- Hadoop大數據實戰權威指南(第2版)
- 數據驅動設計:A/B測試提升用戶體驗
- “互聯網+”時代立體化計算機組
- Python數據分析與挖掘實戰(第3版)
- 計算機組裝與維護(微課版)
- 區域云計算和大數據產業發展:浙江樣板
- Visual Studio 2013 and .NET 4.5 Expert Cookbook
- Expert Python Programming(Third Edition)
- 數據庫應用系統技術
- 算法設計與分析
- 區塊鏈應用開發指南:業務場景剖析與實戰