You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
53 lines
1.9 KiB
53 lines
1.9 KiB
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<PolygonCollider2D>(); |
|
if (polygonCollider2D == null) |
|
{ |
|
polygonCollider2D = obj.AddComponent<PolygonCollider2D>(); |
|
} |
|
|
|
var sprRender = obj.GetComponent<SpriteRenderer>(); |
|
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; |
|
} |
|
}
|
|
|