在網上找了一下,貌似這個實現的並不多,比較多的是一個付費的插件,最初的設想是單純使用着色器就實現的,折騰了一段時間,還是妥協了,用了c#,嗯,先上效果圖:
先解釋一下原理吧,後面補全代碼。
unity開放了opengl的圖形接口給我們,這給了我們在遊戲中繪製自定義圖形的機會。
首先,我們先要獲得目標對象的頂點信息:
Mesh mesh = this.gameObject.GetComponent<MeshFilter>().mesh;
//mesh.vertices
for(int i = 0; i < mesh.triangles.Length; ++i)
{
<span style="white-space:pre"> </span>m_lineVertices.Add(mesh.vertices[mesh.triangles[i]]);
}
注意,首先是獲得了三角形的各頂點的索引,這涉及一個opengl對於重複頂點的一個優化,我們把所有頂點(包括重複的)緩存到一個m_lineVertices,所以m_lineVertices中每兩個連續的頂點之間就可以構成一條線段。
接下來就是繪製線條:
GL.Begin(GL.LINES);
for (int i = 0; i < m_lineVertices.Count/3; ++i)
{
GL.Vertex(m_lineVertices[3*i + 0]);
GL.Vertex(m_lineVertices[3*i + 1]);
GL.Vertex(m_lineVertices[3*i + 1]);
GL.Vertex(m_lineVertices[3*i + 2]);
GL.Vertex(m_lineVertices[3*i + 2]);
GL.Vertex(m_lineVertices[3*i + 0]);
}
GL.End();
下面是完整的c#代碼:
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class Wireframe : MonoBehaviour {
public Color m_lineColor;
Material m_lineMaterial;
List<Vector3> m_lineVertices;
// Use this for initialization
void Start () {
m_lineVertices = new List<Vector3>();
m_lineMaterial = new Material("Shader\"potato/Wireframe\" {SubShader { Pass { Blend SrcAlpha OneMinusSrcAlpha } } }");
m_lineMaterial.hideFlags = HideFlags.HideAndDontSave;
m_lineMaterial.shader.hideFlags = HideFlags.HideAndDontSave;
Mesh mesh = this.gameObject.GetComponent<MeshFilter>().mesh;
//mesh.vertices
for(int i = 0; i < mesh.triangles.Length; ++i)
{
m_lineVertices.Add(mesh.vertices[mesh.triangles[i]]);
}
}
// Update is called once per frame
void Update () {
}
void OnRenderObject()
{
m_lineMaterial.SetPass(0);
GL.MultMatrix(transform.localToWorldMatrix);
GL.Begin(GL.LINES);
for (int i = 0; i < m_lineVertices.Count/3; ++i)
{
GL.Vertex(m_lineVertices[3*i + 0]);
GL.Vertex(m_lineVertices[3*i + 1]);
GL.Vertex(m_lineVertices[3*i + 1]);
GL.Vertex(m_lineVertices[3*i + 2]);
GL.Vertex(m_lineVertices[3*i + 2]);
GL.Vertex(m_lineVertices[3*i + 0]);
}
GL.End();
}
}
上面已經強調m_lineVertices存儲的是所有的頂點包括了重複的頂點,而且,線條的繪製上是沒有跳過已經繪製的線條的,也就是有很多線條已經繪製,但是後面也有可能再繪製一遍,比如一個一個四邊形的斜邊的繪製,實質上這條斜邊繪製了兩遍(因爲組成這個四邊形的兩個三角形公用了這條邊)。