Tristan McPherson
Tristan McPherson

Reputation: 377

How to create a Tile System

Instead of creating separate cases for each tile, what would a better way of doing this be?

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;

                }
            }
        }
    }

Upvotes: 1

Views: 1077

Answers (2)

Robert
Robert

Reputation: 362

I think a good way to do something like this would be to make a "Tile" class. The class could have a Texture2D property for the texture. Then have a draw method in the Tile class that would be called in the game's draw method.

Your Level class could have an array of Tiles rather than integers.

Then your Draw call would be something like this:

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);;
            }

        }
    }

Upvotes: 2

McGarnagle
McGarnagle

Reputation: 102793

There's no need for the case statement, just use a variable.

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
);

If you need to restrict the output to value 0-3 (as is the effect of the case statement), then best to use a conditional if (n >= 0 && n <= 3) { }.

Upvotes: 6

Related Questions