使用Delaunay三角剖分解决求多边形面积的问题
朋友那边最近有个需求,需要框选一个选区,然后根据选区中的点求出面积。并且让我尝试用Delaunay来解决
似乎音译过来应该是德诺类
大致如下:
我在github上找了一个可以用的Delaunay库
https://gist.github.com/miketucker/3795318
(补充:我的Delaunay三角剖分实现:https://www.cnblogs.com/hont/p/15310157.html)
但是需要注意这个只能针对凸多边形创建三角面。
因为创建出来的始终是三角面,把顶点顺序除以3进行遍历
然后根据差乘求平行四边形面积的方法,得到总面积
using UnityEngine; using System.Linq; using System.Collections; [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(MeshRenderer))] public class DelaunayTest : MonoBehaviour { public Transform[] points; MeshFilter meshFilter; Triangulator tr; void Start() { meshFilter = GetComponentInChildren<MeshFilter>() as MeshFilter; } void Update() { tr = new Triangulator(); meshFilter.mesh = tr.CreateInfluencePolygon(points.Select(m => new Vector2(m.localPosition.x, m.localPosition.z)).ToArray()); var vertices = meshFilter.mesh.vertices; var triangles = meshFilter.mesh.triangles; var vertexCount = meshFilter.mesh.triangles.Length; var finalArea = 0f; for (int i = 0; i < meshFilter.mesh.triangles.Length; i += 3) { var a = vertices[triangles[i]]; var b = vertices[triangles[i + 1]]; var c = vertices[triangles[i + 2]]; finalArea += Area(a, b, c); } Debug.Log("Final Area: " + finalArea); } float Area(Vector3 p1, Vector3 p2, Vector3 p3) { float area = Vector3.Cross(p2 - p1, p3 - p2).magnitude * 0.5f; return area; } }