Unity通过脚本实现不规则多边形的碰撞检测 |
您所在的位置:网站首页 › unity六边形UI › Unity通过脚本实现不规则多边形的碰撞检测 |
先上效果图 查找边缘的主要算法就是取到多边形内不共用的边(可以发现只有边缘的边是不被三角形共用的,被三角形公用的边都在内部) 代码: using UnityEngine; using System.Collections.Generic; using UnityEditor; [RequireComponent(typeof(MeshFilter))] [RequireComponent(typeof(PolygonCollider2D))] [ExecuteInEditMode] public class Mesh2DColliderMaker : MonoBehaviour { /// /// 定义一个结构体,用来表示边 /// struct Edge2D { public Vector2 a; public Vector2 b; public override bool Equals(object obj) { if (obj is Edge2D) { var edge = (Edge2D)obj; //An edge is equal regardless of which order it's points are in return (edge.a == a && edge.b == b) || (edge.b == a && edge.a == b); } return false; } public override int GetHashCode() { return a.GetHashCode() ^ b.GetHashCode(); } public override string ToString() { return string.Format("[" + a.x + "," + a.y + "->" + b.x + "," + b.y + "]"); } } MeshFilter filter; PolygonCollider2D polyCollider; void Start() { filter = GetComponent(); polyCollider = GetComponent(); CreatePolygon2DColliderPoints(); } void Update() { } public void CreatePolygon2DColliderPoints() { var edges = BuildEdgesFromMesh(); var paths = BuildColliderPaths(edges); ApplyPathsToPolygonCollider(paths); } /// /// 对多边形碰撞体设置路径 /// /// private void ApplyPathsToPolygonCollider(List paths) { if (paths == null) return; polyCollider.pathCount = paths.Count; for (int i = 0; i |
CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3 |