一、GL簡介
GL是Unity里面的一個底層的圖形庫,其實是GL立即繪制函數 只用當前material的設置。因此除非你顯示指定mat,否則mat可以是任何材質。并且GL可能會改變材質。
GL是立即執行的,如果你在Update()里調用,它們將在相機渲染前執行,相機渲染將會清空屏幕,GL效果將無法看到。通常GL用法是,在camera上貼腳本,并在OnPostRender()里執行。
二、注意事項:
1.GL的線等基本圖元并沒有uv. 所有是沒有貼圖紋理影射的,shader里僅僅做的是單色計算或者對之前的影像加以處理。所以GL的圖形不怎么美觀,如果需要炫麗效果不推薦
2.GL所使用的shader里必須有Cull off指令,否則顯示會變成如下
三、使用GL的一般步驟
1、確定材質球和顏色
2、定義線段的點
3、在Update()里確定所要輸入的點
4、在OnPostRender()里執行劃線命名
四、實現一個例子
畫出從鼠標檢測到的物體的中心點到鼠標輸入的任意一點的線段
貼出代碼,將該腳本掛在主攝像機上
using UnityEngine;
using System.Collections.Generic;
using UnityEngine.Events;
using UnityEngine.EventSystems;
/// <summary>
/// 實現從帶有碰撞器的物體到鼠標移動點之間劃線
/// </summary>
public class m_touch : MonoBehaviour {
public Material mat; //材質球
private GameObject go; //鼠標檢測到的物體
private Vector3 pos1; //頂點一
private Vector3 pos2; //頂點二
private bool isReady = false; //鼠標點是否有新輸入
private bool isFindGo = false; //是否找到物體
void Update()
{
if (Input.GetMouseButtonDown(0))
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
go= hit.collider.gameObject;
if (go.name == "Cube")
{
//將點擊到的物體世界坐標轉為屏幕坐標
Vector2 screenPos1 = Camera.main.WorldToScreenPoint(go.transform.position);
pos1 = new Vector3(screenPos1.x, screenPos1.y, 0);
isFindGo = true;
}
else if (go.name == "Sphere")
{
Vector2 screenPos1 = Camera.main.WorldToScreenPoint(go.transform.position);
pos1 = new Vector3(screenPos1.x, screenPos1.y, 0);
isFindGo = true;
}
}
}
//輸入第二個點
if (Input.GetMouseButton(0) && isFindGo)
{
pos2 = Input.mousePosition;
isReady = true;
}
}
/// <summary>
/// 劃線
/// </summary>
void OnPostRender()
{
if (isFindGo && isReady)
{
GL.PushMatrix();
mat.SetPass(0);
GL.LoadOrtho();
GL.Begin(GL.LINES);
GL.Color(Color.black);
Debug.Log(pos1);
GL.Vertex3(pos1.x / Screen.width, pos1.y / Screen.height, pos1.z);
GL.Vertex3(pos2.x / Screen.width, pos2.y / Screen.height, pos2.z);
Debug.Log(pos2);
GL.End();
GL.PopMatrix();
}
}
}
五、貼出效果圖
GL劃線.gif