我试图通过代码创建一个简单的网格,并试图给出一个与网格大小相同的简单网格对撞机。我尝试了很多不同的东西,但网格对撞机似乎总是比网格本身大。我真的很困惑,任何人都可以解决问题或指出我正确的方向吗?任何帮助表示赞赏。
此外,这是代码:
public class PolygonGenerator : MonoBehaviour
{
private Mesh mesh;
public List<Vector3> newVertices = new List<Vector3>();
public List<int> newTriangles = new List<int>();
private MeshCollider meshCol;
public List<Vector3> colVertices = new List<Vector3> ();
public List<int> colTriangles = new List<int> ();
float x;
float y;
float z;
// Use this for initialization
void Start ()
{
mesh = GetComponent<MeshFilter> ().mesh;
meshCol = gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;
meshCol.convex = true;
x = this.gameObject.transform.position.x;
y = this.gameObject.transform.position.y;
z = this.gameObject.transform.position.z;
GenSquare (x, y);
GenCollider (x, y);
UpdateMesh ();
}
void UpdateMesh()
{
mesh.Clear ();
mesh.vertices = newVertices.ToArray();
mesh.triangles = newTriangles.ToArray();
mesh.Optimize ();
mesh.RecalculateNormals ();
Mesh newMesh = new Mesh ();
newMesh.vertices = colVertices.ToArray ();
newMesh.triangles = colTriangles.ToArray ();
meshCol.sharedMesh = newMesh;
}
void GenSquare(float x, float y)
{
newVertices.Add( new Vector3 (x , y , z ));
newVertices.Add( new Vector3 (x + 1 , y , z ));
newVertices.Add( new Vector3 (x + 1 , y-1 , z ));
newVertices.Add( new Vector3 (x , y-1 , z ));
newTriangles.Add(0);
newTriangles.Add(2);
newTriangles.Add(3);
newTriangles.Add(0);
newTriangles.Add(1);
newTriangles.Add(2);
}
void GenCollider( float x, float y)
{
colVertices.Add( new Vector3 (x , y , z));
colVertices.Add( new Vector3 (x + 1 , y , z));
colVertices.Add( new Vector3 (x + 1 , y-1 , z ));
colVertices.Add( new Vector3 (x , y-1 , z ));
colTriangles.Add (0);
colTriangles.Add (2);
colTriangles.Add (3);
colTriangles.Add (0);
colTriangles.Add (1);
colTriangles.Add (2);
}
void OnCollisionEnter(Collision col)
{
Debug.Log("Collision");
}
void OnTriggerEnter(Collider col)
{
Debug.Log ("Trigger");
}
}
答案 0 :(得分:0)
如果我没弄错的话,你不必手动创建对撞机。您应该能够将组件添加到您使用网格创建的游戏对象中,并且它应该为您计算对撞机。但是如果你仍然想手动创建它,我认为对撞机通常比世界规模的网格大10倍。所以对撞机的大小应该除以10。
这应该解决它:
void GenCollider( float x, float y)
{
colVertices.Add( new Vector3 (x , y , z));
colVertices.Add( new Vector3 (x + 0.1f , y , z));
colVertices.Add( new Vector3 (x + 0.1f , y-0.1f , z ));
colVertices.Add( new Vector3 (x , y-0.1f , z ));
colTriangles.Add (0);
colTriangles.Add (2);
colTriangles.Add (3);
colTriangles.Add (0);
colTriangles.Add (1);
colTriangles.Add (2);
}
我不是百分百肯定的,所以如果你尝试的话请告诉我。