效果
这是一个随机三十个点的最终构成效果。
实现代码
以下是以C#为基础的实现代码,用到了UnityEngine.Vector2类型和v2相关的函数,核心逻辑与Unity不关联,不妨碍移植。
using System.Collections.Generic;
using UnityEngine;
public class UDelaunayResult
{
/// <summary>
/// 三角形列表
/// </summary>
public List<Vector2[]> Triangles;
/// <summary>
/// 边列表
/// </summary>
public List<Vector2[]> Edges;
/// <summary>
/// 顶点列表
/// </summary>
public List<Vector2> Vertexes;
}
public class UDelaunay
{
public static UDelaunayResult GetTriangles2D(List<Vector2> _vertexes)
{
UDelaunayResult result = new UDelaunayResult();
List<Vector2[]> triangles = new List<Vector2[]>();
List<Vector2[]> edges = new List<Vector2[]>();
List<Vector2[]> super = new List<Vector2[]>();
//> 找到最小和最大的点
float minX=0, minY=0, maxX=0, maxY=0;
foreach (var v in _vertexes)
{
if (v.x < minX) minX = v.x;
if (v.y < minY) minY = v.y;
if (v.x > maxX) maxX = v.x;
if (v.y > maxY) maxY = v.y;
}
minX -= 10;
minY -= 10;
maxX += 10;
maxY += 10;
//> 创建超