代码之家  ›  专栏  ›  技术社区  ›  Tristan McPherson

如何创建瓷砖系统

  •  1
  • Tristan McPherson  · 技术社区  · 14 年前

    与其为每个瓦片创建单独的案例,还有什么更好的方法呢?

    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;
    
                    }
                }
            }
        }
    
    2 回复  |  直到 14 年前
        1
  •  6
  •   McGarnagle    14 年前

    不需要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) { } 。

        2
  •  2
  •   Robert    14 年前

    我认为做这样的事情的一个好方法是制作一个“Tile”类。该类可能具有纹理的Texture2D属性。然后在Tile类中有一个draw方法,该方法将在游戏的draw方法中调用。

    Level类可以有一个Tiles数组,而不是整数。

    那么您的Draw调用将是这样的:

    public void Draw(SpriteBatch spriteBatch, Level level)
        {
            for (int row = 0; row < level.tileMap.GetLength(1); row++) {
                for (int col = 0; col < level.tileMap.GetLength(0); col++) {
                    level.tileMap[col, row].Draw(spriteBatch);;
                }
    
            }
        }