2d : Hexagonal Grid Beginner

I am beginner in unity and i need some grid style structure so that i can place game object within cell of that grid according to my previous question.

But I don’t know how to generate hexagonal grid on my 2D plane and how do I instantiate game object within certain cell of the grid?

Thanks to all of you for helping me till now…

5 Answers

5

Generate Hexgrid

[9157-screenshot.20.png*_|9157]

I am going to walk you through on how to do the calculation. The line on the left is 1 unit long. I am going to skip the trigonometry part and go straight to the calculation

The center of the blue hex is ( 0, 0 ), the center of the green is ( root(3) * unit-radius, 0 ), and the center of the red hex is ( root(3) * unit-radius , 1.5 * unit-radius).

By controlling the unit length, you can scale up and scale down the size of the grid. In this example, the radius of the circle is root(3), if you want to have a circle with radius of 1 unit; you can simply divide the calculations by (root(3)/2) to scale up the grid such that they are built from a circle with 1 unit radius.

using UnityEngine;
using System.Collections;

public class HexGrid : MonoBehaviour {
   public Transform spawnThis;   

   public int x = 5;
   public int y = 5;
   
   public float radius = 0.5f;
   public bool useAsInnerCircleRadius = true;

   private float offsetX, offsetY;

   void Start() {
      float unitLength = ( useAsInnerCircleRadius )? (radius / (Mathf.Sqrt(3)/2)) : radius;

      offsetX = unitLength * Mathf.Sqrt(3);
      offsetY = unitLength * 1.5f;

      for( int i = 0; i < x; i++ ) {
         for( int j = 0; j < y; j++ ) {
            Vector2 hexpos = HexOffset( i, j );
            Vector3 pos = new Vector3( hexpos.x, hexpos.y, 0 );
            Instantiate(spawnThis, pos, Quaternion.identity );
         }
      }
   }

   Vector2 HexOffset( int x, int y ) {
      Vector2 position = Vector2.zero;
      
      if( y % 2 == 0 ) {
         position.x = x * offsetX;
         position.y = y * offsetY;
      }
      else {
         position.x = ( x + 0.5f ) * offsetX;
         position.y = y * offsetY;
      }

      return position;
   }
}

Attach this to a empty, assign a default-sphere.

Random/Controlled grid-generation

Random Generation

Make these changes to the script.

public Transform [] spawnThis;

....

Instantiate( spawnThis[ Random.Range(0,spawnThis.length) ], ..., ... );

Controlled Generation

public Transform [] tile; // Water, Ground, Tree tiles

public int W, G, T; //Assign the index of the tiles in the tile[] to here;

private int [][] formation = 
{
  { W, W, W, W, W, W, W },
  { W, G, G, G, G, G, W },
  { W, G, T, T, T, G, W },
  { W, G, G, G, G, G, W },
  { W, W, W, W, W, W, W },
}

....

for( int i = 0; i < formation.length; i++ ) {
   for( int j = 0; j < formation*.length; j++ ) {*

Vector2 hexpos = HexOffset( i, j );
Vector3 pos = new Vector3( hexpos.x, hexpos.y, 0 );
Instantiate(tile[ formation*[j] ], pos, Quaternion.identity );*
}
}
For controlled generation, this is not the best way to do it, the formation will grew very large when you need a large map. To get a better controlled generation of grid, you will need to find out a way to generate the formation instead of defining it in your script.
_*

but all sphere are generated behind of my plane. so what do i need to do?

–

On you screenshot there are hexagons, while the code uses the circle. Did you use a sprite for an hexagon or there is a way to create one programmatic?

–

But if I want to not make a completely full pile but i want some groove between the objects in the grid?

–

If you take a look at the grid, each row is just slid over by 1/2 of the distance between the objects. The length between the rows will be Sqrt(obj_distance^2 - (obj_distance/2)^2).

Attach this to an empty game object and run.

using UnityEngine;
using System.Collections;

public class HexGridLayout : MonoBehaviour {
	public Vector3 v3Center = Vector3.zero;
	public float objDistance =  0.75f;  // Distance apart objects are apart on a row
	public int rows = 12;
	public int cols = 12;
	
	private float rowDist;
	private float rowStart;
	private Vector3 v3Pos; 
	private Vector3 v3Scale = new Vector3(0.2f, 0.2f, 0.2f);
	
	void Start () {
		// Distance the rows are apart Sqrt(objDist^2 - (objDist/2)^2)
		float fT = ((objDistance * objDistance) - ((objDistance * objDistance * 0.25f)));
		rowDist  = Mathf.Sqrt ((objDistance * objDistance) - ((objDistance * objDistance * 0.25f)));
		rowStart = -(cols * objDistance / 2.0f - 0.25f * objDistance);
		v3Pos    = new Vector3(rowStart, rows * rowDist / 2.0f, 0.0f); 
		
		for (int i = 0; i < rows; i++) {
			if ((i % 2) == 1)
				v3Pos.x -= objDistance / 2.0f;
			for (int j = 0; j < cols; j++) {
				GameObject go = GameObject.CreatePrimitive (PrimitiveType.Sphere);
				go.transform.position = v3Pos + v3Center;
				go.transform.localScale = v3Scale;
				v3Pos.x += objDistance;				
			}
			v3Pos.x = rowStart;
			v3Pos.y -= rowDist;
		}
	
	}
}

but still sphere is not visible.. what can be the reason?

–

oh its behind my plane..

–

Thanks @robertbu sir.. your code is also perfect..

–

I did something like this. Here’s the code for my prototype: https://www.khanacademy.org/computer-programming/hex-grid/5117798020546560 The way I got that is that I made irregular hexagons using a pair of squares and a pair of triangles, tiled the plane with those, and took a linear transformation on it to get regular hexagons.

ok Thanks @DanieILC .

–

Just a quick little patch to make this code compatible for a 3D floor, very useful for the hex-based tower defense game I’m working on for my course.

Thanks a lot for the code, it’s saved me a lot of hair pulling! :slight_smile:

Although I am wondering, is there a way to make this spawn from the center outwards rather than from the bottom left corner?

Sorry if this is a corpse post, it’s just the best answer I’ve found so far.

using UnityEngine;
using System.Collections;

public class HexSpawnTestScript : MonoBehaviour
{
    public Transform spawnThis;

    public int x = 5;
    public int z = 5;

    public float radius = 0.5f;
    public bool useAsInnerCircleRadius = true;

    private float offsetX, offsetZ;

    void Start()
    {
        float unitLength = (useAsInnerCircleRadius) ? (radius / (Mathf.Sqrt(3) / 2)) : radius;

        offsetX = unitLength * Mathf.Sqrt(3);
        offsetZ = unitLength * 1.5f;

        for (int i = 0; i < x; i++)
        {
            for (int j = 0; j < z; j++)
            {
                Vector3 hexpos = HexOffset(i, j);
                Vector3 pos = new Vector3(hexpos.x, 0, hexpos.z);
                Instantiate(spawnThis, pos, Quaternion.identity);
            }
        }
    }

    Vector3 HexOffset(int x, int z)
    {
        Vector3 position = Vector3.zero;

        if (z % 2 == 0)
        {
            position.x = x * offsetX;
            position.y = 0;
            position.z = z * offsetZ;
        }
        else
        {
            position.x = (x + 0.5f) * offsetX;
            position.z = z * offsetZ;
        }

        return position;
    }
}

Reviving a dead thread:
I’m trying the provided answer out, but can’t implement

private int [][] formation = { { W, W, W, W, W, W, W }, { W, G, G, G, G, G, W }, { W, G, T, T, T, G, W }, { W, G, G, G, G, G, W }, { W, W, W, W, W, W, W }, }

without it being wholly redlined, telling me that “Array initializers can only be used in a variable or field initializer. Try using a new expression instead.” and “A field initializer cannot reference the non-static field, method, or property ‘name’.”