最近突發奇想,想使用unity3d做一個你畫我猜的游戲,於是就准備動手研究一下,要做這個游戲,首先第一步得想到的就是如何在unity里面畫線,於是上百度,谷歌等各種地方翻抽屜似的查閱了一番,決定用unity開發的OPENGL接口畫線,查閱了Unity官方文檔,首先這是第一次測試的畫線的代碼,代碼腳本需要掛在主攝像機上:
public Material material; public Button button; private List<Vector3> line_list; void Start() { line_list = new List<Vector3>(); button.onClick.AddListener(ClearOnClick); } void ClearOnClick() { line_list.Clear(); } void Update() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if (hit.collider.gameObject.name == "plane") { line_list.Add(Input.mousePosition); } } } void OnPostRender() { //設置該材質通道,0為默認值 material.SetPass(0); //設置繪制2D圖像 GL.LoadOrtho(); //表示開始繪制,繪制累心改為線段 GL.Begin(GL.LINES); int size = line_list.Count; for (int i = 0; i < size - 1; i++) { Vector3 start = line_list[i]; Vector3 end = line_list[i + 1]; //繪制線段 Create_Line(start.x, start.y, end.x, end.y); } GL.End(); //Debug.LogError("畫線"+Time.time); } void Create_Line(float x1, float y1, float x2, float y2) { //繪制線段,需要將屏幕中某個點的像素坐標除以屏幕寬或高 GL.Vertex(new Vector3(x1 / Screen.width, y1 / Screen.height, 0)); GL.Vertex(new Vector3(x2 / Screen.width, y2 / Screen.height, 0)); }
運行效果圖:
看着還不錯,但是有一個缺點,只能夠畫一條線,很顯然這是不符合我們的需求的,我們可以觀察到每一次GL.Begin() 到GL.end畫一條線,那多幾次不就可以畫更多的線,於是我對代碼進行了改良,下面請看第二次測試的代碼:
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class DrawLine : MonoBehaviour { public Material material; public Button button; private List<Vector3> line_list; private Dictionary<int, List<Vector3>> dictionary = new Dictionary<int, List<Vector3>>(); void Start() { line_list = new List<Vector3>(); button.onClick.AddListener(ClearOnClick); } void ClearOnClick() { dictionary.Clear(); } void Update() { Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition); RaycastHit hit; if (Physics.Raycast(ray, out hit)) { if (hit.collider.gameObject.name == "plane") { line_list.Add(Input.mousePosition); } } else { if (line_list.Count > 0 && !dictionary.ContainsKey(dictionary.Count + 1)) { dictionary.Add(dictionary.Count + 1, line_list); line_list = new List<Vector3>(); } } } void OnPostRender() { //設置該材質通道,0為默認值 material.SetPass(0); //設置繪制2D圖像 GL.LoadOrtho(); //遍歷鼠標點的鏈表 foreach (List<Vector3> temp_line in dictionary.Values) { //表示開始繪制,繪制累心改為線段 int size = temp_line.Count; for (int i = 0; i < size - 1; i++) { GL.Begin(GL.LINES); Vector3 start = temp_line[i]; Vector3 end = temp_line[i + 1]; //繪制線段 Create_Line(start.x, start.y, end.x, end.y); GL.End(); } } GL.Flush(); } void Create_Line(float x1, float y1, float x2, float y2) { //繪制線段,需要將屏幕中某個點的像素坐標除以屏幕寬或高 GL.Vertex(new Vector3(x1 / Screen.width, y1 / Screen.height, 0)); GL.Vertex(new Vector3(x2 / Screen.width, y2 / Screen.height, 0)); } }
運行效果圖:
雖然效果達到了,但是畫線的時候有明顯的延時,而且Batches數量也變的特別高,顯然性能方面是有嚴重問題,搗鼓了好久,也沒有找到解決辦法,只能延后了,如果哪位大神看到了這篇帖子,如果有好的解決方法,麻煩留言告訴我,不甚感激!