在Unity3D中利用描點法畫圓——兩個圓融合
阿新 • • 發佈:2018-12-16
這次講述怎麼讓兩個圓融合。
程式碼如下:
int Pos_Z = 0; public int N; //半圓取樣點個數 Vector3 CicleCenter1 = new Vector3(-0.3f, 0, 0);//兩個圓圓心 Vector3 CicleCenter2 = new Vector3(1f, 0, 0); List<List<float>> RoundPoints1 = new List<List<float>>(); List<float> xPoints1 = new List<float>(); List<float> yPoints1 = new List<float>(); List<List<float>> RoundPoints2 = new List<List<float>>(); List<float> xPoints2 = new List<float>(); List<float> yPoints2 = new List<float>(); List<int> DeleteIndex1 = new List<int>(); List<int> DeleteIndex2 = new List<int>(); // Use this for initialization void Start () { for (int i = 0; i < N; i++) { float x1 = -1.3f + i * (2f / N); float y1 = Mathf.Sqrt(1 - Mathf.Pow(x1 + 0.3f, 2)); xPoints1.Add(x1); yPoints1.Add(y1); } for (int i = N; i < 2*N+1; i++) { float x1 = 0.7f - (i-N) * (2f / N); float y1 = -Mathf.Sqrt(1 - Mathf.Pow(x1 + 0.3f, 2)); xPoints1.Add(x1); yPoints1.Add(y1); } for (int i = 0; i < N; i++) { float x2 = 0 + i * (2f / N); float y2 = Mathf.Sqrt(1 - Mathf.Pow(x2 - 1f, 2)); xPoints2.Add(x2); yPoints2.Add(y2); } for (int i = N; i < 2*N+1; i++) { float x2 = 2 - (i-N) * (2f / N); float y2 = -Mathf.Sqrt(1 - Mathf.Pow(x2 - 1f, 2)); xPoints2.Add(x2); yPoints2.Add(y2); } RoundPoints1.Add(xPoints1); RoundPoints1.Add(yPoints1); RoundPoints2.Add(xPoints2); RoundPoints2.Add(yPoints2); #if true //1 //一般判斷距離兩個圓心max大小 for (int i = 0; i < 2 * N + 1; i++)//xPoints1.Count - 1 { float MyDistance1 = Vector3.Distance(CicleCenter1, new Vector3(xPoints1[i], yPoints1[i], 0)); float MyDistance2 = Vector3.Distance(CicleCenter2, new Vector3(xPoints1[i], yPoints1[i], 0)); if (MyDistance1 > MyDistance2) { DeleteIndex1.Add(i); } } for (int i = 0; i < 2 * N + 1; i++) { float MyDistance1 = Vector3.Distance(CicleCenter1, new Vector3(xPoints2[i], yPoints2[i], 0)); float MyDistance2 = Vector3.Distance(CicleCenter2, new Vector3(xPoints2[i], yPoints2[i], 0)); if (MyDistance1 < MyDistance2) { DeleteIndex2.Add(i); } } #endif //刪除交點;倒敘刪除 for (int i = DeleteIndex1.Count - 1; i>=0 ; i--) { xPoints1.RemoveAt(DeleteIndex1[i]); yPoints1.RemoveAt(DeleteIndex1[i]); } for (int i = DeleteIndex2.Count - 1; i >= 0; i--) { xPoints2.RemoveAt(DeleteIndex2[i]); yPoints2.RemoveAt(DeleteIndex2[i]); } } // Update is called once per frame void Update () { #if false 假設兩個圓形,方程分別為 (x + 0.3)2 + y2 = 1 ; ( x - 1 )2 + y2 = 1; #endif for (int i = 0; i < xPoints1.Count-1; i++) { if (i == DeleteIndex1[0]-1) { } else { Debug.DrawLine(new Vector3(xPoints1[i], yPoints1[i], Pos_Z), new Vector3(xPoints1[i + 1], yPoints1[i + 1], Pos_Z),Color.red); } } for (int i = 0; i < xPoints2.Count-1; i++) { if (i == DeleteIndex2[0] - 1) { } else { Debug.DrawLine(new Vector3(xPoints2[i], yPoints2[i], Pos_Z), new Vector3(xPoints2[i + 1], yPoints2[i + 1], Pos_Z), Color.red); } } }
主要是判斷圓上的點距離兩個球心距離,然後判斷距離,若距離小於原來的,便刪除這個點
實現效果如下: