Unity3d BoxCollider线框绘制工具
发表于2018-12-21
有时候想在移动设备或程序运行时看看碰撞体的范围,于是写了这个工具来调试使用,性能不是很高,但是支持显示动态增删的BoxCollider,仅供调试使用。

using System.Collections; using System.Collections.Generic; using UnityEngine; public class BoxColliderGizmo : MonoBehaviour { void Start() { } // Update is called once per frame void OnRenderObject() { var colliders = gameObject.GetComponents<BoxCollider>(); if (colliders == null) { return; } CreateLineMaterial(); lineMaterial.SetPass(0); GL.PushMatrix(); GL.MultMatrix(transform.localToWorldMatrix); for (int i = 0; i < colliders.Length; i++) { var col = colliders[i]; var c = col.center; var size = col.size; float rx = size.x / 2f; float ry = size.y / 2f; float rz = size.z / 2f; Vector3 p0, p1, p2, p3; Vector3 p4, p5, p6, p7; p0 = c + new Vector3(-rx,-ry,rz); p1 = c + new Vector3(rx, -ry, rz); p2 = c + new Vector3(rx, -ry, -rz); p3 = c + new Vector3(-rx, -ry, -rz); p4 = c + new Vector3(-rx, ry, rz); p5 = c + new Vector3(rx, ry, rz); p6 = c + new Vector3(rx, ry, -rz); p7 = c + new Vector3(-rx, ry, -rz); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p0); GL.Vertex(p1); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p1); GL.Vertex(p2); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p2); GL.Vertex(p3); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p0); GL.Vertex(p3); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p4); GL.Vertex(p5); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p5); GL.Vertex(p6); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p6); GL.Vertex(p7); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p4); GL.Vertex(p7); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p0); GL.Vertex(p4); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p1); GL.Vertex(p5); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p2); GL.Vertex(p6); GL.End(); GL.Begin(GL.LINES); GL.Color(Color.red); GL.Vertex(p3); GL.Vertex(p7); GL.End(); } GL.PopMatrix(); } static Material lineMaterial; static void CreateLineMaterial() { if (!lineMaterial) { // Unity has a built-in shader that is useful for drawing // simple colored things. Shader shader = Shader.Find("Hidden/Internal-Colored"); lineMaterial = new Material(shader); lineMaterial.hideFlags = HideFlags.HideAndDontSave; // Turn on alpha blending lineMaterial.SetInt("_SrcBlend", (int)UnityEngine.Rendering.BlendMode.SrcAlpha); lineMaterial.SetInt("_DstBlend", (int)UnityEngine.Rendering.BlendMode.OneMinusSrcAlpha); // Turn backface culling off lineMaterial.SetInt("_Cull", (int)UnityEngine.Rendering.CullMode.Off); // Turn off depth writes lineMaterial.SetInt("_ZWrite", 0); } } }

把代码放在想要显示的物体上就行了,只会显示它自身的,不会显示子物体的,只会显示盒碰撞体,不显示网格碰撞体。
如社区发表内容存在侵权行为,您可以点击这里查看侵权投诉指引