Skip to content

Instantly share code, notes, and snippets.

@unitycoder
Created November 26, 2022 17:54
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 unitycoder/f4ea8071a5d6ccceef210550bc5f0cf3 to your computer and use it in GitHub Desktop.
Save unitycoder/f4ea8071a5d6ccceef210550bc5f0cf3 to your computer and use it in GitHub Desktop.
Unity Draw Hilbert Curve
// https://youtu.be/hPXJN4PkB28
using System.Collections;
using UnityEngine;
public class Hilbert : MonoBehaviour
{
int order = 5;
int N;
int width = 64;
Vector3[] hpoints = new Vector3[] { new Vector3(0, 0, 0), new Vector3(0, 1, 0), new Vector3(1, 1, 0), new Vector3(1, 0, 0) };
IEnumerator Start()
{
N = (int)Mathf.Pow(2, order);
int total = N * N;
Vector3[] path = new Vector3[total];
Debug.Log("total points: " + total);
for (int i = 0; i < total; i++)
{
path[i] = HilbertCurve(i);
float len = width / (float)N;
path[i] *= len;
path[i] += new Vector3(len / 2f, len / 2f, 0);
}
Debug.Log("Drawing");
for (int i = 1; i < total; i++)
{
float hue = Remap(i, 0, total, 0, 1);
var c = Color.HSVToRGB(hue, 1, 1);
Debug.DrawLine(path[i - 1], path[i], c, 15);
if (i % 255 == 0) yield return 0;
}
}
Vector3 HilbertCurve(int i)
{
int index = i & 3;
Vector3 v = hpoints[index];
for (int j = 1; j < order; j++)
{
i = i >> 2;
index = i & 3;
float len = Mathf.Pow(2, j);
switch (index)
{
case 0:
var temp = v.x;
v.x = v.y;
v.y = temp;
break;
case 1:
v.y += len;
break;
case 2:
v.x += len;
v.y += len;
break;
case 3:
var temp3 = len - 1 - v.x;
v.x = len - 1 - v.y;
v.y = temp3;
v.x += len;
break;
default:
break;
}
}
return v;
}
float Remap(float source, float sourceFrom, float sourceTo, float targetFrom, float targetTo)
{
return targetFrom + (source - sourceFrom) * (targetTo - targetFrom) / (sourceTo - sourceFrom);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment