与其为每个图 block 创建单独的案例,不如这样做更好的方法是什么?
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;
}
}
}
}
不需要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
);
如果您需要将输出限制为值 0-3(如 case 语句的效果),那么最好使用条件 if (n >= 0 && n <= 3) { }
.
我是一名优秀的程序员,十分优秀!