torsdag 6. februar 2014

Create a map of your world in LibGDX

Creating a map of your world in LibGDX. Assuming you have a game world consisting of a 2d array map2d[sizeX][sizeY], here is a simple way to create a map of your world using a Pixmap and a Texture that is updated at a regular interval (maybe once every second or so):

public class Map {
    private Texture texture;
    private Pixmap map;
    private int size;

    public Map(Universe universe) {
        this.universe = universe;
        size = universe.getSize();
        texture = new Texture(size, size, Pixmap.Format.RGB565);
        map = new Pixmap(size, size, Pixmap.Format.RGB565);
        init();
    }

    // Static elements
    public void init() {
        for (int x = 0; x < size; x++) {
            for (int y = 0; y < size; y++) {
                Color color = getColorForUniverse(Universe.map2d[x][y]);
                map.setColor(color);
                map.drawPixel(x, y);
            }
        }
    }

    // Dynamic element
    public void spot(GameBody gameBody, Color color) {
        map.setColor(color);
        map.drawPixel(Math.round(gameBody.getPosition().x), Math.round(gameBody.getPosition().y));
    }

    private Color getColorForUniverse(int val) {
        switch (val) {
            case 0: // Empty space
                return Color.WHITE;
            default: // Any other space
                return Color.GRAY;
        }
    }

    // Draw the map
    public void draw(SpriteBatch spriteBatch, float x, float y) {
        texture.draw(map, 0, 0);
        spriteBatch.draw(texture, x, y,
                size / 4, size / 4,
                size / 2, size / 2,
                1f, 1f, 0, 0, 0, texture.getWidth(), texture.getHeight(), false, true);
    }
}
At a regular interval you would then call init() once followed by a spot() for each GameBody you want to plot on your map.