- Home /
Question by
gilles14 · Apr 01, 2019 at 03:32 PM ·
meshunity 2dmeshcollider
Why collisions on meshcollider 2d doesn't work?
Hello, I want to generate random terrain with collisions and I use mesh generator from Unity Wiki for it. It works fine.
Now I want to add collisions and I found the same problem here https://answers.unity.com/questions/171571/dynamic-mesh-collider.html
but answer doesn't work for me.
I have gameObject with attached script to it, but when other gameObjects goes through Mesh object, collision doesn't happen
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class PolygonTester : MonoBehaviour {
void Start () {
// Create Vector2 vertices
Vector2[] vertices2D = new Vector2[] {
new Vector2 (0, 0),
new Vector2 (0, 1),
new Vector2 (1, 1),
new Vector2 (1, 2),
new Vector2 (0, 2),
new Vector2 (0, 3),
new Vector2 (3, 3),
new Vector2 (3, 2),
new Vector2 (2, 2),
new Vector2 (2, 1),
new Vector2 (3, 1),
new Vector2 (3, 0),
};
// Use the triangulator to get indices for creating triangles
Triangulator tr = new Triangulator (vertices2D);
int[] indices = tr.Triangulate ();
// Create the Vector3 vertices
Vector3[] vertices = new Vector3[vertices2D.Length];
for (int i = 0; i < vertices.Length; i++) {
vertices[i] = new Vector3 (vertices2D[i].x, vertices2D[i].y, 0);
}
// Create the mesh
Mesh msh = new Mesh ();
msh.vertices = vertices;
msh.triangles = indices;
msh.RecalculateNormals ();
msh.RecalculateBounds ();
// Set up game object with mesh;
gameObject.AddComponent (typeof (MeshRenderer));
MeshFilter filter = gameObject.AddComponent (typeof (MeshFilter)) as MeshFilter;
filter.mesh = msh;
MeshCollider myMC = GetComponent<MeshCollider> ();
myMC.sharedMesh = null;
myMC.sharedMesh = msh;
}
}
Comment
Your answer