using UnityEngine;
using System.Collections;
using System.Collections.Generic;
public class DrawLineTest : MonoBehaviour
{
/// <summary>
/// 繪製線段的材質
/// </summary>
public Material material;
/// <summary>
/// 鼠標線段鏈表
/// </summary>
private List<Vector3> lineInfo;
void Start()
{
lineInfo = new List<Vector3>();
}
void Update()
{
if (Input.GetMouseButton(0))
{
//將鼠標的位置存儲進鏈表
lineInfo.Add(Input.mousePosition);
}
}
/// <summary>
/// 系統調用的繪製方法
/// </summary>
void OnPostRender()
{
if (!material) return;
//設置材質通道,0爲默認值
material.SetPass(0);
//設置繪製2D圖像
GL.LoadOrtho();
//開始繪製,表示繪製線段
GL.Begin(GL.LINES);
int size = lineInfo.Count;
//遍歷鼠標點的鏈表
for (int i = 0; i < size - 1; i++)
{
Vector3 start = lineInfo[i];
Vector3 end = lineInfo[i + 1];
//繪製線段
DrawLine(start.x, start.y, end.x, end.y);
//lineInfo.Clear();
}
GL.End();
}
void DrawLine(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));
}
}it