码迷,mamicode.com
首页 > 编程语言 > 详细

Unity GL画折线

时间:2018-06-23 19:10:20      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:sha   opengl   IV   ase   point   调用   awl   new   error   

新建一个脚本,这个物体得挂在有摄像机组件的物体上才能生效

OnPostRender() 这个函数才会被自动调用(类似生命周期自动调用)

然后就可以代码画线了,原理是openGL的画线

 

using UnityEngine;
using System.Collections;
using System.Collections.Generic;

/// <summary>
/// GL画图
/// </summary>
public class GLDraw : UnityNormalSingleton<GLDraw> {

    public Transform p1;
    public Transform p2;
    private List<Vector2> pointList;
    private bool isOpen;

    private Material mat;
    private Shader shader;

    private void Start()
    {
        pointList = new List<Vector2>();
        shader = Shader.Find("Unlit/Color");
        mat = new Material(shader);
        mat.SetColor("Main Color", Color.black);
    }

    public void DrawLine(List<object> list)
    {
        pointList.Clear();
        for (int i = 0; i < list.Count; i++)
        {
            Vector2 screenPos = (Vector2)list[i];
            pointList.Add(new Vector2(screenPos.x, Screen.height - screenPos.y));
        }
    }

    public void ShowLine(bool b)
    {
        isOpen = b;
    }

    void OnPostRender()
    {
        if (!isOpen)
        {
            return;
        }

        //mat = new Material(Shader.Find("Unlit/Color"));
        //Debug.Log("调用");
        //if (!mat)
        //{
        //    Debug.LogError("Please Assign a material on the inspector");
        //    return;
        //}
        GL.PushMatrix(); //保存当前Matirx
        mat.SetPass(0); //刷新当前材质
        GL.LoadPixelMatrix();//设置pixelMatrix
        GL.Color(Color.yellow);
        GL.Begin(GL.LINES);

        //画2次,奇偶数画连续折线法
        for (int i = 0; i < pointList.Count; i++)
        {
            GL.Vertex3(pointList[i].x, pointList[i].y, 0);
        }
        for (int i = 1; i < pointList.Count; i++)
        {
            GL.Vertex3(pointList[i].x, pointList[i].y, 0);
        }

     //单次画线发
//GL.Vertex3(0, 0, 0);//GL.Vertex3(Screen.width, Screen.height, 0);
     //固定2点画
//GL.Vertex3(p1.position.x, p1.position.y, 0); //GL.Vertex3(p2.position.x, p2.position.y, 0); GL.End(); GL.PopMatrix();//读取之前的Matrix } }

 

Unity GL画折线

标签:sha   opengl   IV   ase   point   调用   awl   new   error   

原文地址:https://www.cnblogs.com/sanyejun/p/9217613.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!