Unity中使用GL在Camera上画线
正交绘制
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class joint
{
public Vector3 org;
public Vector3 end;
}
public class GLTest : MonoBehaviour {
public Color lineColor = Color.red;
public Shader fadeShader = null;
[Range(0.0f,0.5f)]
public float space;
private Material fadeMaterial = null;
void Awake()
{
// create the fade material
fadeMaterial = (fadeShader != null) ? new Material(fadeShader) : new Material(Shader.Find("Unlit/Color"));
}
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
void OnPostRender()
{
fadeMaterial.SetPass(0);
fadeMaterial.color = lineColor;
GL.PushMatrix();
GL.LoadOrtho();
GL.Begin(GL.LINES);
Vector3 directionx = (new Vector3(0.5f, 0.5f, 0) - Vector3.zero).normalized;
Vector3 directiony = (new Vector3(0.5f, 0.5f, 0) - new Vector3(1, 0, 0)).normalized;
GLDrawLine(new Vector3(0, 0, 0) + directionx * space, new Vector3(0, 1, 0) - directiony * space);
GLDrawLine(new Vector3(0, 0, 0) + directionx * space, new Vector3(1, 0, 0) + directiony * space);
GLDrawLine(new Vector3(0, 1, 0) - directiony * space, new Vector3(1, 1, 0) - directionx * space);
GLDrawLine(new Vector3(1, 0, 0) + directiony * space, new Vector3(1, 1, 0) - directionx * space);
GL.End();
GL.PopMatrix();
}
void GLDrawLine(Vector3 beg, Vector3 end)
{
GL.Vertex3(beg.x, beg.y, beg.z);
GL.Vertex3(end.x, end.y, end.z);
}
}
如果要给线加宽度就不能使用GL.LINES,而要使用GL.QUADS。就是每一条线都是一个矩形的片代替。
3D绘制
以上方法是在Camra正交矩阵下绘制,如果要在世界坐标系中绘制就不需要调GL.LoadOrtho();这时就需要将Camera视图上的点转化成世界坐标系中的点来绘制。
...
float nearClip = mainCamera.nearClipPlane + 0.00001f;
//left
Vector3 p1 = mainCamera.ViewportToWorldPoint(new Vector3(space, space, nearClip));
Vector3 p2 = mainCamera.ViewportToWorldPoint(new Vector3(space, 1 - space, nearClip));
Vector3 p3 = mainCamera.ViewportToWorldPoint(new Vector3(linewidth + space, 1 - space, nearClip));
Vector3 p4 = mainCamera.ViewportToWorldPoint(new Vector3(linewidth + space, space, nearClip));
GL.Vertex(p1);
GL.Vertex(p2);
GL.Vertex(p3);
GL.Vertex(p4);
...