您的位置:首页 > 移动开发 > Unity3D

Unity3D开发之利用GL画曲线

2013-10-30 10:37 190 查看


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

public class DrawLine : MonoBehaviour {

	//绘制线段材质  
    public Material material;  
    private List<Vector3> lineInfo;
	private bool startDraw = false;
	Event e;
	
	void Start () {
	//初始化鼠标线段链表  
        lineInfo = new List<Vector3>();  
		
	}
	
	void OnGUI(){
		e = Event.current;
	}
	
	// Update is called once per frame
	void Update () {

        if(e.type == EventType.MouseDown)
        {
            startDraw = true;
            
        }
        if(e.type==EventType.MouseDrag)
        {
            if(startDraw == true){
				//将每次鼠标经过的位置存储进链表  
        		lineInfo.Add(Input.mousePosition); 
			}
        }
        if(e.type==EventType.MouseUp)
        {
            startDraw = false;
			lineInfo.Clear();
        }
		
		
	}
	
	
	//GL的绘制方法系统回调  
    void OnPostRender() 
    { 
        if(!material) 
        { 
            Debug.LogError("material == null");  
            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];  
            //绘制线  
            DrawLineFun(start.x,start.y,end.x,end.y);  
        } 
        //结束绘制  
        GL.End();  
           
    } 
       
    void DrawLineFun(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));  
    } 
}


直接把此脚本绑定在相机上面就可以了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: