Unity3D引擎技術交流QQ群:【21568554】
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,來調整圓的位置,旋轉,縮放。
