根据Mesh 来生成 Polygon Collider 2D:
在编辑器中编辑多边形碰撞器2D是不可能的,因为有数千个顶点。
想要支持具有多个非连接组件的网格?没问题
ColliderCreator C# Code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 |
using System.Collections.Generic; using UnityEngine; public class ColliderCreator : MonoBehaviour { void Start() { // Stop if no mesh filter exists or there's already a collider if (GetComponent<PolygonCollider2D>() || GetComponent<MeshFilter>() == null) { return; } // Get triangles and vertices from mesh int[] triangles = GetComponent<MeshFilter>().mesh.triangles; Vector3[] vertices = GetComponent<MeshFilter>().mesh.vertices; // Get just the outer edges from the mesh's triangles (ignore or remove any shared edges) Dictionary<string, KeyValuePair<int, int>> edges = new Dictionary<string, KeyValuePair<int, int>>(); for (int i = 0; i < triangles.Length; i += 3) { for (int e = 0; e < 3; e++) { int vert1 = triangles[i + e]; int vert2 = triangles[i + e + 1 > i + 2 ? i : i + e + 1]; string edge = Mathf.Min(vert1, vert2) + ":" + Mathf.Max(vert1, vert2); if (edges.ContainsKey(edge)) { edges.Remove(edge); } else { edges.Add(edge, new KeyValuePair<int, int>(vert1, vert2)); } } } // Create edge lookup (Key is first vertex, Value is second vertex, of each edge) Dictionary<int, int> lookup = new Dictionary<int, int>(); foreach (KeyValuePair<int, int> edge in edges.Values) { if (lookup.ContainsKey(edge.Key) == false) { lookup.Add(edge.Key, edge.Value); } } // Create empty polygon collider PolygonCollider2D polygonCollider = gameObject.AddComponent<PolygonCollider2D>(); polygonCollider.pathCount = 0; // Loop through edge vertices in order int startVert = 0; int nextVert = startVert; int highestVert = startVert; List<Vector2> colliderPath = new List<Vector2>(); while (true) { // Add vertex to collider path colliderPath.Add(vertices[nextVert]); // Get next vertex nextVert = lookup[nextVert]; // Store highest vertex (to know what shape to move to next) if (nextVert > highestVert) { highestVert = nextVert; } // Shape complete if (nextVert == startVert) { // Add path to polygon collider polygonCollider.pathCount++; polygonCollider.SetPath(polygonCollider.pathCount - 1, colliderPath.ToArray()); colliderPath.Clear(); // Go to next shape if one exists if (lookup.ContainsKey(highestVert + 1)) { // Set starting and next vertices startVert = highestVert + 1; nextVert = startVert; // Continue to next loop continue; } // No more verts break; } } } } |
原文地址:https://www.h3xed.com/programming/automatically-create-polygon-collider-2d-from-2d-mesh-in-unity