-
项目需求我需要利用鼠标动态绘制三维多边形实体,
并赋予
collider
属性,
unity3d
中提
供了
mesh
类,可
以用程序动态绘制网格,难点在于在绘制网格时需要将网格三角划分并按
顺时针指定顶点
的三角序列。
这就需要对网格顶点按顺时针方向选三个顶点做三角检测。
有
现成的相关算法,我结合
unity3d
写了一个
C#
版的。
这里
用到了循环队列。可以将下面代码
考出来后缀改为
*.CS
p>
更好看些,注意文件名为
MeshTest
.CS
using UnityEngine;
using
c;
using System;
using
public class MeshTest :
MonoBehaviour {
public float heigth = 0.0f;
public Camera cam;
public Material material;
private bool
buildStatus = false;
private Ray ray
private RaycastHit hit;
private Ray ray2
private RaycastHit hit2;
private Vector3[]
newVertices;
private ist vtAarry = new ist();
//
动态添加数组只能用
ArrayList
void
Update()
{
if (buildStatus)
{
if
(seButtonDown (1))
{
ray
= PointToRay(osition);
if(t(ray,out
hit))
{
(.x);
(.z);
}
}
}
if
(seButtonDown (0))
{
ray2 = PointToRay(osition);
if(t(ray2,out
hit2))
{
(
网格
();
if( ==
{
(
网格
2
(
网格
}
}
}
}
void OnGUI()
{
if ( (new Rect (10, 10, 100,
25),
建模
{
int i = 0;
int
j = 0;
int mLength = / 2;
newVertices =
new Vector3[mLength];
GameObject g = new
GameObject();
ponent
ponent
=
MeshFilter
meshFilter = ponent
//get the mesh
//
Mesh mymesh =
for (i= 0;
i
{
newVertices[i]
=
new
Vector3(((f
loat)vtAarry[j]-(float)vtAarry[0]),10,((float)vtAa
rry[j+1]-(float)vtAarry[1]));
j
+= 2;
}
mymesh =
CreateMesh(mLength,newVertices,mymesh);
on
=
new
Vector3((fl
oat)vtAarry[0],heigth,(float)vtAarry[1]);
ponent
//GameObject
clone
//clone
=
Instantiate(g,new
Vector3((f
loat)vtAarry[0],heigth,(float)vtAarry[1]),ty) as
GameObject;
}
if ( (new Rect (10, 40,
100, 25),
选点
{
buildStatus =
true;
}
}
Mesh CreateMesh(int mLength,Vector3[]
Vertices,Mesh mymesh)
{
p>
//
利用
mesh
类画不规则多边形
//the triangle arraylist
//
int i = 0;
int j = 0;
int numTiangle = (mLength -
2) * 3;
Vector3[] normals;
Vector2[] newUV;
int[] newTiangles;
newTiangles =
new int[numTiangle];
normals = new Vector3[mLength];
newUV = new
Vector2[mLength];
es = Vertices;
ChangeToTriangle (newTiangles);
les
= newTiangles;
for(i = 0;i
{
normals[i] =
}
s = normals;
for(i = 0;i
{
newUV[i] = new
Vector2(newVertices[i].x,newVertices[i].y);
}
= newUV;