Unity GL 画圆

Posted WFUF

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Unity GL 画圆相关的知识,希望对你有一定的参考价值。

Unity下GL没有画圆的函数,只能自己来了。

如果能帮到大家,我也很高兴。

虽然没有画圆的函数,但是能画直线,利用这一点,配合微积分什么的,就可以画出来了。反正就是花很多连在一起的直线,每条直线足够短的时候,就足够圆了

 1 void DrawCircle(float x, float y, float z, float r, float accuracy)
 2 {
 3     GL.PushMatrix ();
 4     //绘制2D图像    
 5     GL.LoadOrtho ();
 6 
 7     float stride = r * accuracy;
 8     float size = 1 / accuracy;
 9     float x1 = x, x2 = x, y1 = 0, y2 = 0;
10     float x3 = x, x4 = x, y3 = 0, y4 = 0;
11 
12     double squareDe;
13     squareDe = r * r - Math.Pow (x - x1, 2);
14     squareDe = squareDe > 0 ? squareDe : 0;
15     y1 = (float)(y + Math.Sqrt (squareDe));
16     squareDe = r * r - Math.Pow (x - x1, 2);
17     squareDe = squareDe > 0 ? squareDe : 0;
18         y2 = (float)(y - Math.Sqrt (squareDe));
19     for (int i = 0; i < size; i++) {
20         x3 = x1 + stride;
21         x4 = x2 - stride;
22         squareDe = r * r - Math.Pow (x - x3, 2);
23         squareDe = squareDe > 0 ? squareDe : 0;
24                 y3 = (float)(y + Math.Sqrt (squareDe));
25         squareDe = r * r - Math.Pow (x - x4, 2);
26         squareDe = squareDe > 0 ? squareDe : 0;
27         y4 = (float)(y - Math.Sqrt (squareDe));
28   
29         //绘制线段
30                 GL.Begin (GL.LINES);
31         GL.Color (Color.blue);
32         GL.Vertex (new Vector3 (x1 / Screen.width, y1 / Screen.height, z));
33         GL.Vertex (new Vector3 (x3 / Screen.width, y3 / Screen.height, z));
34         GL.End ();
35 GL.Begin (GL.LINES);
36         GL.Color (Color.blue);
37         GL.Vertex (new Vector3 (x2 / Screen.width, y1 / Screen.height, z));    
38         GL.Vertex (new Vector3 (x4 / Screen.width, y3 / Screen.height, z));
39         GL.End ();
40                 GL.Begin (GL.LINES);
41         GL.Color (Color.blue);
42         GL.Vertex (new Vector3 (x1 / Screen.width, y2 / Screen.height, z));    
43         GL.Vertex (new Vector3 (x3 / Screen.width, y4 / Screen.height, z));
44         GL.End ();
45                 GL.Begin (GL.LINES);
46         GL.Color (Color.blue);
47         GL.Vertex (new Vector3 (x2 / Screen.width, y2 / Screen.height, z));    
48         GL.Vertex (new Vector3 (x4 / Screen.width, y4 / Screen.height, z));
49         GL.End ();
50 
51         x1 = x3;
52         x2 = x4;
53         y1 = y3;
54         y2 = y4;
55     }
56     GL.PopMatrix ();
57 }

参数分别为: x,y,z 中心点三维坐标, r 圆的半径, accuracy 精度,精度越小,越圆

 

如有错误,请不吝指教

以上是关于Unity GL 画圆的主要内容,如果未能解决你的问题,请参考以下文章

Unity3D:Gizmos画圆(转载)

怎样在Unity 中绘制多边形

openGL画圆

shader 画圆,椭圆

Unity GL画折线

OpenGL用鼠标移动画圆