How to set an appropriate PolygonCollider2D offset and size

Hello everyone. I’m working on the shadows detection in my game. For each object that has a shadow I’ve added an empty child object with the PolygonCollider2D, which is updated from code - I detect the shadow’s corners and update its collider by calling the SetPath() method. The transform coordinates of each of this child objects are set to (0,0,0).

First issue is with the resulting colliders. Their points are placed correctly (they’re connected with red lines), but colliders are placed aside (green lines):


The offset on this collider is set to (0,0) and if I change it manually it will work fine.

The second issue is the with colliders sizes. In the previous picture I’ve manually set it’s size to (2,2,0) instead of the default (1,1,0) like in the next picture:
8227947--1074975--upload_2022-6-23_18-29-58.png

Could anyone please explain how does the PolygonCollider2D work? Does it connect the points of the Path and then resize the resulting collider and move it by an offset? And could you please suggest how can I fix this so I don’t have to set these parameters manually for each object (It’s not just repetitive but also could result in setting an inaccurate values)?

Collider (and mesh vertex) coordinates are always in local coordinates and thus are affected by the position, rotation and scaling in effect at that point in your hierarchy.

It appears that you perhaps have either scaling or offsets not taken into account.

To prove it, put this code on a known not-scaled, not-rotated object at (0,0,0). Does it work?

1 Like

Yes, it works fine on a not-scaled and not-rotated objects on the default position. Now I understand why it happens, and I’ve fixed this by just transforming the global coordinates to local. Thanks a lot!

1 Like