求解多个点的中心---基于平均距离
Unity C# 计算多个点的中心
计算中心点的位置,根据不同的计算要求有不同的计算方法,如计算位置重心、计算最短距离的中心、计算平均距离的中心。本文主要解决简单的平均距离的中点计算。最后,在Unity中实现中心计算。
C#脚本
- 使用List 列表存储需要计算的点Points的位置
- centerPoint.x =SUM(Points[1].x, Points[2].x, …Points[Count].x ) / Point.Count
centerPoint.y =SUM(Points[1].y, Points[2].y, …Points[Count].y ) / Point.Count - Gizmos可视化绘图
1. public List<Transform> Points = new List<Transform>();
2. // Calculate_CenterPoint函数
public Vector3 Calculate_CenterPoint(List<Transform> Points)
{
int total = Points.Count;
float lat = 0, lon = 0;
foreach (Transform p in Points)
{
lat += p.transform.position.x;// * Mathf.PI / 180;
lon += p.transform.position.z;// * Mathf.PI / 180;
}
lat /= total;
lon /= total;
Vector3 centerPoint = new Vector3(lat, Points[0].position.y, lon) ;
Debug.Log("Center " + centerPoint);
return centerPoint;
}
3. //可视化
void OnDrawGizmos()
{
Gizmos.color = new Color(20, 0, 0);
Gizmos.DrawSphere(centerPoint, 0.2f);
}
Unity结果
-
三个点坐标分别如下:
-
计算所得其平均距离中点-----红色圆圈标注
中心点坐标:
-
多个点基于平均距离的中心位置
===> 四个点
===> 六个点
写在最最最后
这里只是基于平均距离实现了中心点的计算,还有更为复杂的重心计算以及最近点的中心计算,具体的大家可以看这个链接 http://www.geomidpoint.com/calculation.html
此外,发现Unity居然还有一个经纬度地理位置的GeoCoordinate Class,有空有机会吧,可以研究研究。
好啦~ 感谢!
最后的最后
朋友发了个谢师宴的朋友圈,点了个赞,大晚上的翻看了他的网易云动态,害,也许是放下了吧,大家都放下了吧。可心里还是不太舒服,想,就不想了吧,就这样吧。
顺利毕业,穿金戴银~