Skip to content

Instantly share code, notes, and snippets.

@farshidce
Created April 25, 2016 19:26
Show Gist options
  • Save farshidce/8c0136933b76fb9e1d028e0a784e4715 to your computer and use it in GitHub Desktop.
Save farshidce/8c0136933b76fb9e1d028e0a784e4715 to your computer and use it in GitHub Desktop.
using UnityEngine;
using System.Collections;
public class HexaGrid : MonoBehaviour
{
public Material mat;
private Vector3 startVertex;
private Vector3 mousePos;
void Start()
{
startVertex = Vector3.zero;
}
void Update()
{
mousePos = Input.mousePosition;
if (Input.GetKeyDown(KeyCode.P))
{
startVertex = mousePos;
startVertex.z = 0;
}
}
void OnPostRender()
{
if (!mat)
{
Debug.LogError("Please Assign a material on the inspector");
return;
}
GL.PushMatrix();
mat.SetPass(0);
GL.Color(Color.green);
GL.LoadOrtho();
GL.Begin(GL.LINES);
// second parameter should be the second position of the mouse
Vector3[] points = CalculatePoints(startVertex, new Vector3(startVertex.x + 50, startVertex.y - 50, 0));
for(int i = 0; i < points.Length; i++)
{
GL.Vertex(new Vector3(points[i].x / Screen.width, points[i].y / Screen.height, 0));
}
GL.End();
GL.PopMatrix();
}
Vector3[] CalculatePoints(Vector3 from, Vector3 to)
{
Vector3[] points = new Vector3[4];
float diameter = Vector3.Distance(from, to);
Vector3 direction = (to - from).normalized;
float length = diameter / 2;
Vector3 p0p1vector = (Quaternion.AngleAxis(60, Vector3.forward) * direction);
Vector3 p1 = from + (p0p1vector * length);
direction = (p1 - from).normalized;
Vector3 p1p2vector = (Quaternion.AngleAxis(-60, Vector3.forward) * direction);
Vector3 p2 = p1 + (p1p2vector * length);
direction = (p2 - p1).normalized;
Vector3 p2p3vector = (Quaternion.AngleAxis(-60, Vector3.forward) * direction);
Vector3 p3 = p2 + (p2p3vector * length);
direction = (p3 - p2).normalized;
Vector3 p3p4vector = (Quaternion.AngleAxis(-60, Vector3.forward) * direction);
Vector3 p4 = p3 + (p3p4vector * length);
direction = (p4 - p3).normalized;
Vector3 p4p5vector = (Quaternion.AngleAxis(-60, Vector3.forward) * direction);
Vector3 p5 = p4 + (p4p5vector * length);
direction = (p5 - p4).normalized;
Vector3 p5p6vector = (Quaternion.AngleAxis(-60, Vector3.forward) * direction);
Vector3 p6 = p5 + (p5p6vector * length);
print(string.Format("length {0} diameter {1} p0 {2} p1 {3} p2 {4} p3 {5} p4 {6} p5 {7} p6 {8}", length, diameter, from, p1, p2, p3, p4, p5, p6));
return new Vector3[]{from, p1, p2, p3, p4, p5, p6};
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment