Skip to content

Instantly share code, notes, and snippets.

@phosphoer
Created May 27, 2022 18:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phosphoer/568520cf04c585895e2a5804691358ac to your computer and use it in GitHub Desktop.
Save phosphoer/568520cf04c585895e2a5804691358ac to your computer and use it in GitHub Desktop.
Hex Grid Math
using UnityEngine;
public struct HexCoord
{
public float q;
public float r;
public float s;
public HexCoord(float q, float r)
{
this.q = q;
this.r = r;
this.s = -q - r;
}
public HexCoord(float q, float r, float s)
{
this.q = q;
this.r = r;
this.s = s;
}
}
public static class HexMath
{
public const float kSqrt3 = 1.73205080757f;
public const float kHexSize = 0.5f;
public const float kHexWidth = kSqrt3 * kHexSize;
public const float kHexHeight = 2 * kHexSize;
public static HexCoord CartesianToHex(Vector3 pos)
{
HexCoord hex;
hex.q = (kSqrt3 / 3f * pos.x - 1f / 3f * pos.z) / kHexSize;
hex.r = (2f / 3f * pos.z) / kHexSize;
hex.s = -hex.q - hex.r;
return hex;
}
public static Vector3 HexToCartesian(HexCoord hex)
{
Vector3 pos = Vector3.zero;
pos.x = kHexSize * (kSqrt3 * hex.q + kSqrt3 / 2f * hex.r);
pos.z = kHexSize * (3f / 2f * hex.r);
return pos;
}
public static HexCoord RoundHex(HexCoord hex)
{
HexCoord rounded = new HexCoord(Mathf.Round(hex.q), Mathf.Round(hex.r), Mathf.Round(hex.s));
HexCoord diff = new HexCoord(Mathf.Abs(rounded.q - hex.q), Mathf.Abs(rounded.r - hex.r), Mathf.Abs(rounded.s - hex.s));
if (diff.q > diff.r && diff.q > diff.s)
rounded.q = -rounded.r - rounded.s;
else if (diff.r > diff.s)
rounded.r = -rounded.q - rounded.s;
else
rounded.s = -rounded.q - rounded.r;
return rounded;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment