之前有做过UV版线框,觉得有些效果无法实现,所以继续研究线框制作。直到看到了unity内置的GL方法,就像打开了新世界,能做的东西又变多了。
今天先试试画线的功能。
using UnityEngine;
public class SS_17 : MonoBehaviour
{
private Material lineMat;
public Color lineColor;
Mesh mesh;
Vector3[] lines;
public Mesh Mesh
{
get
{
if (mesh == null)
{
mesh = GetComponent<MeshFilter>().mesh;
}
return mesh;
}
set
{
mesh = value;
}
}
public Vector3[] Lines
{
get
{
if (lines == null || lines.Length == 0)
{
var vertices = Mesh.vertices;
var triangles = Mesh.triangles;
lines = new Vector3[triangles.Length];
int count = 0;
for (int i = 0; i < triangles.Length / 3; i++)
{
lines[count++] = vertices[triangles[i * 3]];
lines[count++] = vertices[triangles[i * 3 + 1]];
lines[count++] = vertices[triangles[i * 3 + 2]];
}
}
return lines;
}
set
{
lines = value;
}
}
public Material LineMat
{
get
{
if (lineMat == null)
{
lineMat = new Material(Shader.Find("MyShader/SS_17"));
}
return lineMat;
}
set
{
lineMat = value;
}
}
private void OnRenderObject()
{
LineMat.SetPass(0); //LineMat作为临时材质,设置好属性后会叠加到原有的材质上 ,而且不管原有的材质是什么Shader,就相当于在原有图案上再画一层
GL.PushMatrix();
LineMat.SetColor("_LineColor", lineColor);
//转换到世界坐标
GL.MultMatrix(transform.localToWorldMatrix);
GL.Begin(GL.LINES); //貌似没法设置宽度,用多条线?
for (int i = 0; i < Lines.Length / 3; i++)
{
GL.Vertex(Lines[i * 3]);
GL.Vertex(Lines[i * 3 + 1]);
GL.Vertex(Lines[i * 3 + 1]);
GL.Vertex(Lines[i * 3 + 2]);
GL.Vertex(Lines[i * 3 + 2]);
GL.Vertex(Lines[i * 3]);
}
GL.End();
GL.PopMatrix();
}
}
Shader "MyShader/SS_17" {
Properties{
_LineColor ("LineColor", Color) = (1,1,1,1)
}
SubShader {
Pass {
Tags { "RenderType"="Opaque"}
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
};
struct v2f
{
half4 pos : SV_POSITION;
};
fixed4 _LineColor;
v2f vert(appdata_base v)
{
v2f o;
o.pos = UnityObjectToClipPos(v.vertex);
return o;
}
fixed4 frag(v2f i) : SV_Target
{
return _LineColor;
}
ENDCG
}
}
}
返回目录:https://blog.csdn.net/yzy1987523/article/details/106676451