Skip to content

Instantly share code, notes, and snippets.

@LuxGiammi
Created June 23, 2018 13:29
Show Gist options
  • Save LuxGiammi/8c1e17feecf7d3c33a1a493657a4d153 to your computer and use it in GitHub Desktop.
Save LuxGiammi/8c1e17feecf7d3c33a1a493657a4d153 to your computer and use it in GitHub Desktop.
Generation of an hexagon tiled floor - implementation in Unity3D
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class GenerateHexFloor : MonoBehaviour {
public GameObject Hexagon;
public uint Radius;
public float HexSideMultiplier = 1;
private const float sq3 = 1.7320508075688772935274463415059F;
// Use this for initialization
void Start () {
//Point of the next hexagon to be spawned
Vector3 currentPoint = transform.position;
if (Hexagon.transform.localScale.x != Hexagon.transform.localScale.z)
{
Debug.LogError("Hexagon has not uniform scale: cannot determine its side. Aborting");
return;
}
//Spawn scheme: nDR, nDX, nDL, nUL, nUX, End??, UX, nUR
Vector3[] mv = {
new Vector3(1.5f,0, -sq3*0.5f), //DR
new Vector3(0,0, -sq3), //DX
new Vector3(-1.5f,0, -sq3*0.5f), //DL
new Vector3(-1.5f,0, sq3*0.5f), //UL
new Vector3(0,0, sq3), //UX
new Vector3(1.5f,0, sq3*0.5f) //UR
};
int lmv = mv.Length;
float HexSide = Hexagon.transform.localScale.x * HexSideMultiplier;
for (int mult = 0; mult <= Radius; mult++)
{
int hn = 0;
for (int j = 0; j < lmv; j++)
{
for (int i = 0; i < mult; i++, hn++)
{
GameObject h = Instantiate(Hexagon, currentPoint, Hexagon.transform.rotation, transform);
h.name = string.Format("Hex Layer: {0}, n: {1}", mult, hn);
currentPoint += (mv[j] * HexSide);
}
if (j == 4)
{
GameObject h = Instantiate(Hexagon, currentPoint, Hexagon.transform.rotation, transform);
h.name = string.Format("Hex Layer: {0}, n: {1}", mult, hn);
currentPoint += (mv[j] * HexSide);
hn++;
if (mult == Radius)
break; //Finished
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment