u3d游戏中显示模型的网格

本文介绍如何在Unity中使用C#实现3D模型的线框效果。通过获取模型顶点并利用OpenGL绘制线段,实现了对3D模型的轮廓勾勒。文章提供了完整的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在网上找了一下,貌似这个实现的并不多,比较多的是一个付费的插件,最初的设想是单纯使用着色器就实现的,折腾了一段时间,还是妥协了,用了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存储的是所有的顶点包括了重复的顶点,而且,线条的绘制上是没有跳过已经绘制的线条的,也就是有很多线条已经绘制,但是后面也有可能再绘制一遍,比如一个一个四边形的斜边的绘制,实质上这条斜边绘制了两遍(因为组成这个四边形的两个三角形公用了这条边)。

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

梁potato

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值