前言 我看网上大多都是根据父物体来计算子物体的中心点 没有找到计算数组的中心点
先上代码 有错误再修改,这个代码也是网上的,稍微修改一下 unity 就可以用
/// <summary>
/// 获取中心点坐标
/// </summary>
/// <param name="p"></param>
/// <returns></returns>
public Vector2 GetCenterPoint(Vector3[] p)
{
Vector2 ptCenter = new Vector3(0, 0);
int i, j;
double ai, atmp = 0, xtmp = 0, ytmp = 0;
if (p == null)
throw new ArgumentNullException("获取多边形中心点坐标时传入的参数为空。");
if (p.Length == 1)
return p[0];
if ((p.Length == 2) || (p.Length == 3 && p[0] == p[2]))
return new Vector3((p[1].x + p[0].x) / 2, (p[1].y + p[0].y) / 2);
int n = p.Length;
for (i = n - 1, j = 0; j < n; i = j, j++)
{
ai = p[i].x * p[j].y - p[j].x * p[i].y;
atmp += ai;
xtmp += (p[j].x + p[i].x) * ai;
ytmp += (p[j].y + p[i].y) * ai;
}
if (atmp != 0)
{
ptCenter.x = Convert.ToInt32(xtmp / (3 * atmp));
ptCenter.y = Convert.ToInt32(ytmp / (3 * atmp));
}
return ptCenter;
}