Skip to content

Instantly share code, notes, and snippets.

@TJHeuvel
Created October 6, 2020 19:11
Show Gist options
  • Save TJHeuvel/b3d064f26c248d11379c72dae7fbe85f to your computer and use it in GitHub Desktop.
Save TJHeuvel/b3d064f26c248d11379c72dae7fbe85f to your computer and use it in GitHub Desktop.
Hexes
using System;
using UnityEditor;
using UnityEngine;
using UnityEngine.InputSystem;
using System.Linq;
class Test : MonoBehaviour
{
[SerializeField, Range(0, 1)] private float[] chances = new float[6];
[CustomEditor(typeof(Test))]
class TestClassEditor : Editor
{
float radius = 68;
public override void OnInspectorGUI()
{
base.OnInspectorGUI();
var target = base.target as Test;
float max = target.chances.Sum();
GUILayout.Space(200);
var colors = new Color[6]
{
Color.green,
Color.red,
Color.blue,
Color.yellow,
Color.cyan,
Color.magenta
};
var angles = new float[6]
{
60,
60,
60,
60,
60,
60
};
var r = EditorGUILayout.GetControlRect(GUILayout.Height(100));
var center = r.center;
float angle = 30f;
for (int i = 0; i < 6; i++)
{
Handles.color = colors[i];
float nextAngle = angle + (target.chances[i] / max * 360f);
for (float a = angle; a < nextAngle; a++)
{
Vector2 p1 = getPositionAtAngle(center, angle, radius),
p2 = getPositionAtAngle(center, nextAngle, radius);
Handles.DrawAAConvexPolygon(p1, p2, center);
}
GUI.color = Color.black;
EditorGUIHelper.DrawLine(
getPositionAtAngle(center, angle, radius),
getPositionAtAngle(center, nextAngle, radius),
2f);
EditorGUIHelper.DrawLine(
center,
getPositionAtAngle(center, angle, radius), 1f);
angle = nextAngle;
}
}
Vector2 getPositionAtAngle(Vector2 center, float angle, float radius)
{
angle -= 90f;
angle *= Mathf.Deg2Rad;
return new Vector2(center.x + radius * Mathf.Cos(angle),
center.y + radius * Mathf.Sin(angle));
}
Vector2 getPosition(Vector2 center, float a, float radius, int corner)
{
return getPositionAtAngle(center, a * corner, radius);
}
Vector2 getPosition(Vector2 center, float radius, int corner)
{
return getPosition(center, 60, radius, corner);
}
}
}
public static class EditorGUIHelper
{
public static void DrawLine(Vector2 pointA, Vector2 pointB, float width)
{
Matrix4x4 matrixBackup = GUI.matrix;
float angle = Mathf.Atan2(pointB.y - pointA.y, pointB.x - pointA.x) * 180f / Mathf.PI;
float length = Vector2.Distance(pointA, pointB);
GUIUtility.RotateAroundPivot(angle, pointA);
GUI.DrawTexture(new Rect(pointA.x, pointA.y, length, width), Texture2D.whiteTexture);
GUI.matrix = matrixBackup;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment