Unity3d 使用Gizmos画一个圆圈
程序员文章站
2022-03-02 23:39:56
gizmos是场景视图里的一个可视化调试工具。在做项目过程中。我们常常会用到它,比如:绘制一条射线等。unity3d 4.2版本号截至。眼下仅仅提供了绘制射线,线段,网格球体,实体球体,网格立方体,实...
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,来调整圆的位置,旋转,缩放。
补充:基于unity3d使用linerender组件绘制圆线
在此记录一下使用unity3d 的linerender绘制线的过程,经过测试linerender与opengl的gl_line_strip绘制方式一样,因此计算完点之后需要把起始点即为终点,多算一个点才算闭合。
代码如下:
using system.collections; using system.collections.generic; using unityengine; using unityengine.ui; public class drawlines: monobehaviour { public float m_radius = 1.0f; public material m_material; public float m_linewidth = 1.0f; private list<vector3> vpath = new list<vector3>(); // start is called before the first frame update void start() { int count = 60; for (int i=1; i<= (count+1); i++) { if(i == (count+1)) { float x = mathf.cos(2 * mathf.pi / count) * m_radius; float y = transform.localposition.y; float z = mathf.sin(2 * mathf.pi / count) * m_radius; vpath.add(new vector3(x, y, z)); } else { float x = mathf.cos(2 * mathf.pi / count * i) * m_radius; float y = transform.localposition.y; float z = mathf.sin(2 * mathf.pi / count * i) * m_radius; vpath.add(new vector3(x, y, z)); } } gameobject linegroup = new gameobject("linegroup"); gameobject lineobject = new gameobject("radarline"); linerenderer line = lineobject.addcomponent<linerenderer>(); line.material = m_material; line.useworldspace = false; line.positioncount = vpath.count; line.startwidth = m_linewidth; line.endwidth = m_linewidth; line.setpositions(vpath.toarray()); } // update is called once per frame void update() { } }
运行一下看一下效果:
以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有错误或未考虑完全的地方,望不吝赐教。
下一篇: jQuery实现影院选座订座效果