Unity 凸包算法-切线算法

凸包算法-切线算法

先上图吧
Unity 凸包算法-切线算法_第1张图片
Unity 凸包算法-切线算法_第2张图片

方法:

  • 先吧这些点放在二维坐标系中 找出最下边的点1
  • 以这个点为原点 水平正方形为底边 和其他点组成的夹角最小的那个点 就是我们寻找的第二个点
  • *现在就以上一个点和所选的点连线作为下一次夹角计算的底边(注意这个底边的方向是从上一个点到这个点的向量方向)
  • 以此类推 直到找个重复的点停止

代码片段

private void CalculationPoint()
        {
            List posVec = new List();
            GameObject sourceObj = null;
            Vector3 sourcePoint = pointList[0].transform.localPosition;
            foreach (GameObject obj in pointList)
            {
                Vector3 objVec = obj.transform.localPosition;
                if (sourceObj == null)
                {
                    sourceObj = obj;
                }
                else
                {
                    if (sourcePoint.y > objVec.y)
                    {
                        sourceObj = obj;
                        sourcePoint = objVec;
                    }
                }
            }
            lineObjList.Add(sourceObj);

            Vector3 sourcePoint2 = new Vector3(sourcePoint.x + 5, sourcePoint.y, sourcePoint.z);
            Vector3 forward = (sourcePoint2 - sourcePoint).normalized;
            LoopFun(sourceObj, forward);

        }

        private void LoopFun( GameObject sourceObj, Vector3 forward)
        {
            float angle1 = 360;
            float leng = 0;
            Vector3 newForward = Vector3.zero;
            GameObject nobj = null;

            Vector3 sourceVec = sourceObj.transform.localPosition;
            foreach (GameObject obj in pointList)
            {
                if (obj == sourceObj) continue;
                Vector3 objVec = obj.transform.localPosition;
                Vector3 nf = (objVec - sourceVec).normalized;
                float lg = Vector3.Distance(sourceVec, objVec);
                float angle = Angle(sourceVec, sourceVec + forward, objVec);
                if ((angle < angle1) || (angle == angle1 && leng < lg))
                {
                    angle1 = angle;
                    nobj = obj;
                    newForward = nf;
                    leng = lg;
                }
            }

            bool isList = JuagePoint(nobj);
            if (!isList)
            {
                lineObjList.Add(nobj);
                LoopFun(nobj, newForward);
            }
        }

你可能感兴趣的:(unity3d,算法)