最近突发奇想,想使用unity3d做一个你画我猜的游戏,于是就准备动手研究一下,要做这个游戏,首先第一步得想到的就是如何在unity里面画线,于是上百度,谷歌等各种地方翻抽屉似的查阅了一番,决定用unity开发的OPENGL接口画线,查阅了Unity官方文档,首先这是第一次测试的画线的代码,代码脚本需要挂在主摄像机上:
publicMaterial material;publicButton button;private Listline_list;voidStart()
{
line_list= new List();
}voidClearOnClick()
{
line_list.Clear();
}voidUpdate()
{
Ray ray=Camera.main.usePosition);
RaycastHit hit;if (Physics.Raycast(ray, outhit))
{if (llider.gameObject.name == "plane")
{
line_list.usePosition);
}
}
}voidOnPostRender()
{//设置该材质通道,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, floaty2)
{//绘制线段,需要将屏幕中某个点的像素坐标除以屏幕宽或高
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画一条线,那多几次不就可以画更多的线,于是我对代码进行了改良,下面请看第二次测试的代码:
usingSystem.Collections;usingSystem.Collections.Generic;usingUnityEngine;usingUnityEngine.UI;public classDrawLine : MonoBehaviour
{publicMaterial material;publicButton button;private Listline_list;private Dictionary> dictionary = new Dictionary>();voidStart()
{
line_list= new List();
}voidClearOnClick()
{
dictionary.Clear();
}voidUpdate()
{
Ray ray=Camera.main.usePosition);
RaycastHit hit;if (Physics.Raycast(ray, outhit))
{if (llider.gameObject.name == "plane")
{
line_list.usePosition);
}
}else{if (line_list.Count > 0 && !dictionary.ContainsKey(dictionary.Count + 1))
{
dictionary.Add(dictionary.Count+ 1, line_list);
line_list= new List();
}
}
}voidOnPostRender()
{//设置该材质通道,0为默认值
material.SetPass(0);//设置绘制2D图像
GL.LoadOrtho();//遍历鼠标点的链表
foreach (List temp_line indictionary.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, floaty2)
{//绘制线段,需要将屏幕中某个点的像素坐标除以屏幕宽或高
GL.Vertex(new Vector3(x1 / Screen.width, y1 / Screen.height, 0));
GL.Vertex(new Vector3(x2 / Screen.width, y2 / Screen.height, 0));
}
}运行效果图:
虽然效果达到了,但是画线的时候有明显的延时,而且Batches数量也变的特别高,显然性能方面是有严重问题,捣鼓了好久,也没有找到解决办法,只能延后了,如果哪位大神看到了这篇帖子,如果有好的解决方法,麻烦留言告诉我,不甚感激!
本文发布于:2024-01-30 14:06:53,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170659481520537.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |