- Home /
Add a polygon collider 2D using vertices of edge collider
Hello! Is it possible to create a polygon collider on a complex shape (it has a mesh/mesh renderer/edge colliders) based on points of actual edge colliders? I made a simple script but it is not working, i tried to get edge colliders points as an array and add them to a new added polygon collider... Of course it doesn't work. :)
using System.Collections;
public class EdgeToPolygon : MonoBehaviour {
private PolygonCollider2D myCollider;
private Vector2[] tempArray;
// Update is called once per frame
void Start (){
EdgeCollider2D testEdge = GetComponent<EdgeCollider2D>();
Vector2[] tempArray = testEdge.points;
}
void Update () {
if (Input.GetKeyDown("space"))
gameObject.AddComponent <PolygonCollider2D>();
if (Input.GetKeyDown("enter"))
myCollider = gameObject.GetComponent<PolygonCollider2D>();
myCollider.points = tempArray;
}
}
Any tips? Each kind of help is really appreciated! ^_^
Thanks, Kaem
Comment
Answer by Keseren · Dec 23, 2015 at 04:30 PM
void AddPolyColliderFromMesh(GameObject Object) {
if (Object.GetComponent<PolygonCollider2D>() == null) {
Object.AddComponent<PolygonCollider2D>();
}
Vector3[] Verticles = Object.GetComponent<MeshFilter>().mesh.vertices;
int[] Triangles = Object.GetComponent<MeshFilter>().mesh.triangles;
Vector2[] Points = new Vector2[Triangles.Length];
for (int n = 0; n < Triangles.Length; n++) {
Points[n] = Vector3To2(Verticles[Triangles[n]]);
}
Object.GetComponent<PolygonCollider2D>().points = Points;
}
I used this in my script, if you still need help then try this.