Unity3D:Gizmos画圆

来源:互联网 发布:纯种狗的悲哀知乎 编辑:程序博客网 时间:2024/04/27 21:45

Gizmos是场景视图里的一个可视化调试工具。在做项目过程中,我们经常会用到它,例如:绘制一条射线等。


Unity3D 4.2版本截至,目前只提供了绘制射线,线段,网格球体,实体球体,网格立方体,实体立方体,图标,GUI纹理,以及摄像机线框。

如果需要绘制一个圆环还需要自己写代码。文章出处狗刨学习网


  1. [size=3]using UnityEngine;
  2. using System;

  3. public class HeGizmosCircle : MonoBehaviour
  4. {
  5.        public Transform m_Transform;
  6.        public float m_Radius = 1; // 圆环的半径
  7.        public float m_Theta = 0.1f; // 值越低圆环越平滑
  8.        public Color m_Color = Color.green; // 线框颜色
  9.        
  10.        void Start()
  11.        {
  12.               if (m_Transform == null)
  13.               {
  14.                      throw new Exception("Transform is NULL.");
  15.               }
  16.        }

  17.        void OnDrawGizmos()
  18.        {
  19.               if (m_Transform == null) return;
  20.               if (m_Theta < 0.0001f) m_Theta = 0.0001f;

  21.               // 设置矩阵
  22.               Matrix4x4 defaultMatrix = Gizmos.matrix;
  23.               Gizmos.matrix = m_Transform.localToWorldMatrix;

  24.               // 设置颜色
  25.               Color defaultColor = Gizmos.color;
  26.               Gizmos.color = m_Color;

  27.               // 绘制圆环
  28.               Vector3 beginPoint = Vector3.zero;
  29.               Vector3 firstPoint = Vector3.zero;
  30.               for (float theta = 0; theta < 2 * Mathf.PI; theta += m_Theta)
  31.               {
  32.                      float x = m_Radius * Mathf.Cos(theta);
  33.                      float z = m_Radius * Mathf.Sin(theta);
  34.                      Vector3 endPoint = new Vector3(x, 0, z);
  35.                      if (theta == 0)
  36.                      {
  37.                             firstPoint = endPoint;
  38.                      }
  39.                      else
  40.                      {
  41.                             Gizmos.DrawLine(beginPoint, endPoint);
  42.                      }
  43.                      beginPoint = endPoint;
  44.               }

  45.               // 绘制最后一条线段
  46.               Gizmos.DrawLine(firstPoint, beginPoint);

  47.               // 恢复默认颜色
  48.               Gizmos.color = defaultColor;

  49.               // 恢复默认矩阵
  50.               Gizmos.matrix = defaultMatrix;
  51.        }
  52. }[/size]
复制代码


把代码拖到一个GameObject上,关联该GameObject的Transform,然后就可以在Scene视图窗口里显示一个圆了。




通过调整Transform的Position,Rotation,Scale,来调整圆的位置,旋转,缩放。

0 0
原创粉丝点击