按照正常的思维,先将多边形进行三角剖分,生成网格,再添加碰撞器,去实现业务逻辑
多边形三角化是件麻烦事,还需要考虑多边形的凹凸性,有没有洞等
其实可以反其道而行,先添加碰撞器,通过碰撞器生成mesh,代码比较简单,直接上代码
using System.Collections; using System.Collections.Generic; using UnityEngine; public class CreateMesh : MonoBehaviour { public Vector2[] points; void Start() { //EdgeColliderTest(); PolygonColliderTest(); } void PolygonColliderTest() { PolygonCollider2D poly = gameObject.AddComponent<PolygonCollider2D>(); poly.points = points; Mesh mesh = poly.CreateMesh(true, true); MeshFilter mf = gameObject.AddComponent<MeshFilter>(); mf.mesh = mesh; MeshRenderer mr = gameObject.AddComponent<MeshRenderer>(); mr.material = new Material(Shader.Find("Standard")); } void EdgeColliderTest() { EdgeCollider2D edge = gameObject.AddComponent<EdgeCollider2D>(); edge.points = points; edge.edgeRadius = 0.1f; Mesh mesh = edge.CreateMesh(true, true); MeshFilter mf = gameObject.AddComponent<MeshFilter>(); mf.mesh = mesh; MeshRenderer mr = gameObject.AddComponent<MeshRenderer>(); mr.material = new Material(Shader.Find("Standard")); } }
多边形效果:
线段效果:
如果对你有帮助,支持一下原创,点个赞吧
标签:mf,多边形,AddComponent,gameObject,生成,Unity,mesh,points From: https://www.cnblogs.com/Jason-c/p/17579191.html