In Progress
📝

Map System Of Strategis

The Hex Grid Problem Rendering a hex grid sounds simple until you need to handle click detection, pathfinding, and neighbor […]

← Back to Project

The Hex Grid Problem

So I ended up following their guide and modified it slightly to make a hexagon grid. So I have a prefab for a generic tile type. When I run GenerateHexGrid() it generates a grid of tiles in runtime.

The Hexagon Grid

void GenerateHexGrid()
    {
        int tileIndex = 0;

        HexCoord center = new HexCoord(0, 0);
        Vector2 centerPos = GetWorldPosition(center);
        Tile centerTile = InstantiateTile(ctilePrefab, tileIndex, center, centerPos, 0);
        tileIndex++;

        for (int ring = 1; ring < numOfRings; ring++)
        {
            HexCoord pos = new HexCoord(-ring, ring);

            for (int side = 0; side < 6; side++)
            {
                for (int i = 0; i < ring; i++)
                {
                    Vector2 worldPos = GetWorldPosition(pos);
                    Tile tile = InstantiateTile(tilePrefab, tileIndex, pos, worldPos, ring);
                    tileIndex++;
                    pos = GetNextPosition(pos, side);
                }
            }
        }

        Debug.Log($"Generated {allTiles.Count} tiles.");
    }

The coordinate system

Every hex has a (q, r) coordinate:

public Vector2 GetWorldPosition(HexCoord hexPos)
    {
        float x = hexSize * (Mathf.Sqrt(3) * hexPos.q + Mathf.Sqrt(3) / 2 * hexPos.r);
        float y = hexSize * (3f / 2 * hexPos.r);
        return new Vector2(x, y) + origin;
    }

    public HexCoord GetHexCoord(Vector2 pos)
    {
        int q = Mathf.RoundToInt((Mathf.Sqrt(3)/3 * pos.x - 1 / 3 * pos.y) / hexSize);
        int r = Mathf.RoundToInt((2f / 3 * pos.y) / hexSize);
        return new HexCoord(q, r);
    }

So now that we have a grid, we need to define what a Tile is…

Tile

Types of tiles:

We have 4 different types of tile. There isn’t much difference between them visually but like behavior wise they are different and I consider them as separate types from the beginning to avoid confusion later on.

Scroll to Top