不是为每个瓷砖创建单独的案例,更好的方法是什么?
public void Draw(SpriteBatch spriteBatch, Level level)
{
for (int row = 0; row < level._intMap.GetLength(1); row++) {
for (int col = 0; col < level._intMap.GetLength(0); col++) {
switch (level._intMap[col, row]) {
case 0:
spriteBatch.Draw(_texture, new Rectangle(row * _tileWidth, col * _tileHeight, _tileWidth, _tileHeight), new Rectangle(0 * _tileWidth, 0 * _tileHeight, _tileWidth, _tileHeight), Color.White);
break;
case 1:
spriteBatch.Draw(_texture, new Rectangle(row * _tileWidth, col * _tileHeight, _tileWidth, _tileHeight), new Rectangle(1 * _tileWidth, 0 * _tileHeight, _tileWidth, _tileHeight), Color.White);
break;
case 2:
spriteBatch.Draw(_texture, new Rectangle(row * _tileWidth, col * _tileHeight, _tileWidth, _tileHeight), new Rectangle(2 * _tileWidth, 0 * _tileHeight, _tileWidth, _tileHeight), Color.White);
break;
case 3:
spriteBatch.Draw(_texture, new Rectangle(row * _tileWidth, col * _tileHeight, _tileWidth, _tileHeight), new Rectangle(3 * _tileWidth, 0 * _tileHeight, _tileWidth, _tileHeight), Color.White);
break;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
不需要case语句,只需使用变量即可.
var n = level._intMap[col, row];
spriteBatch.Draw(_texture,
new Rectangle(row * _tileWidth, col * _tileHeight, _tileWidth, _tileHeight),
new Rectangle(n * _tileWidth, 0 * _tileHeight, _tileWidth, _tileHeight), Color.White
);
Run Code Online (Sandbox Code Playgroud)
如果需要将输出限制为值0-3(因为case语句的效果),那么最好使用条件if (n >= 0 && n <= 3) { }.
| 归档时间: |
|
| 查看次数: |
888 次 |
| 最近记录: |