Search code examples
java2dsandboxtile

Java 2D-Tile based game - Creating tile objects from an id


I have been making a tile (block) based 2D side-view game.

So far I have the basic rendering and world generation going. Each tile (block) has its own class for different actions or properties that block has. But I need a way to create these objects using a number.

So every tile (block) has its own id, and so I can use that id to create new objects. And for a inventory system.


Solution

  • The way I do is hardcoding every Tile with it's number.

    public Tile getTile(int id, int x_pos, int y_pos)
    {
        switch (id)
        {
            case 0:  return new GroundTile(x_pos, y_pos); break;
            case 1:  return new SpringTile(x_pos, y_pos); break;
            ...
        }
        return Tile.getEmptyTile(x_pos, y_pos);
    }
    

    I doubt that you are creating tile based level for the game. If so you can use Tiled Map Editor