using System.Collections; using System.Collections.Generic; using UnityEditor; using UnityEngine; public static class GenPolygonCollider { static float tileWidth = 1.0f; static float tileHeight = 0.5f; static float halfTileWidth = tileWidth / 2; static float halfTileHeight = tileHeight / 2; [MenuItem("Tools/ResourceEditor/GeneratePolygonCollider")] public static void GeneratePolygonCollider() { GameObject obj = Selection.activeGameObject; PolygonCollider2D polygonCollider2D = obj.GetComponent(); if (polygonCollider2D == null) { polygonCollider2D = obj.AddComponent(); } var sprRender = obj.GetComponent(); var sprite = sprRender.sprite; Bounds bounds = sprite.bounds; Vector4 border = sprite.border; var minPos = sprRender.transform.TransformPoint(bounds.center - new Vector3(bounds.extents.x - border.x / sprite.pixelsPerUnit, bounds.extents.y - border.y / sprite.pixelsPerUnit)); var maxPos = sprRender.transform.TransformPoint(bounds.center + new Vector3(bounds.extents.x - border.z / sprite.pixelsPerUnit, bounds.extents.y - border.w / sprite.pixelsPerUnit)); float sprWidth = maxPos.x - minPos.x; float sprHeight = maxPos.y - minPos.y; int sizeX = 2; int sizeY = 3; Vector2 left = MapToLocalPos(sizeX, 0); Vector2 top = MapToLocalPos(sizeX, sizeY); Vector2 right = MapToLocalPos(0, sizeY); Vector2 bottom = Vector2.zero; polygonCollider2D.points = new[] { bottom, left, top, right }; } public static Vector2 MapToLocalPos(int row, int col) { Vector2 worldPos = new Vector2(); worldPos.x = (col - row) * halfTileWidth; worldPos.y = (row + col) * halfTileHeight; return worldPos; } }