Unity3D:Gizmos畫圓


Gizmos是場景視圖里的一個可視化調試工具。在做項目過程中,我們經常會用到它,例如:繪制一條射線等。

Unity3D 4.2版本截至,目前只提供了繪制射線,線段,網格球體,實體球體,網格立方體,實體立方體,圖標,GUI紋理,以及攝像機線框。

如果需要繪制一個圓環還需要自己寫代碼。

using UnityEngine;
using System;

public class HeGizmosCircle : MonoBehaviour
{
       public Transform m_Transform;
       public float m_Radius = 1; // 圓環的半徑
       public float m_Theta = 0.1f; // 值越低圓環越平滑
       public Color m_Color = Color.green; // 線框顏色
       
       void Start()
       {
              if (m_Transform == null)
              {
                     throw new Exception("Transform is NULL.");
              }
       }

       void OnDrawGizmos()
       {
              if (m_Transform == null) return;
              if (m_Theta < 0.0001f) m_Theta = 0.0001f;

              // 設置矩陣
              Matrix4x4 defaultMatrix = Gizmos.matrix;
              Gizmos.matrix = m_Transform.localToWorldMatrix;

              // 設置顏色
              Color defaultColor = Gizmos.color;
              Gizmos.color = m_Color;

              // 繪制圓環
              Vector3 beginPoint = Vector3.zero;
              Vector3 firstPoint = Vector3.zero;
              for (float theta = 0; theta < 2 * Mathf.PI; theta += m_Theta)
              {
                     float x = m_Radius * Mathf.Cos(theta);
                     float z = m_Radius * Mathf.Sin(theta);
                     Vector3 endPoint = new Vector3(x, 0, z);
                     if (theta == 0)
                     {
                            firstPoint = endPoint;
                     }
                     else
                     {
                            Gizmos.DrawLine(beginPoint, endPoint);
                     }
                     beginPoint = endPoint;
              }

              // 繪制最后一條線段
              Gizmos.DrawLine(firstPoint, beginPoint);

              // 恢復默認顏色
              Gizmos.color = defaultColor;

              // 恢復默認矩陣
              Gizmos.matrix = defaultMatrix;
       }
}

把代碼拖到一個GameObject上,關聯該GameObject的Transform,然后就可以在Scene視圖窗口里顯示一個圓了。

通過調整Transform的Position,Rotation,Scale,來調整圓的位置,旋轉,縮放。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM