Can I do a 2D collider operation (2D collider subtraction)?

Like the image attached, I want to get a 2D collider that covers the gray area, it’s the result that the biggest collider subtracts the areas of these two smaller colliders inside.

What I have are the references to these three colliders.

I just want to, at runtime programmally, create one or serveral 2D colliders that altogether covers only the gray area in the image below

Thanks very much.

5205083--517862--Collider.jpg

1 Like

We don’t provide the ability to subtract collider geometry from other colliders although we do provide the ability to add collider geometry using the CompositeColldier2D. It wouldn’t be that hard to add this as a feature to CompositeCollider2D I guess but as of today, this isn’t something it can do.

You can however use the PolygonCollider2D and feed it any geometry you want in the form of paths (list of vertex). So for instance, the image above is a path for the outer box then you define two more paths for the sub-regions and these will form holes.

Here’s an example script that assumes there’s a PolygonCollider2D on the same GameObject and will produce a similar set-up as above:

using UnityEngine;

public class SetGeomety : MonoBehaviour
{
    void Start()
    {
        var collider = GetComponent<PolygonCollider2D>();

        var path0 = new Vector2[]
        {
            new Vector2(-4.0f, -4.0f),
            new Vector2(4.0f, -4.0f),
            new Vector2(4.0f, 4.0f),
            new Vector2(-4.0f, 4.0f)
        };

        var path1 = new Vector2[]
        {
            new Vector2(-1.0f, -1.0f),
            new Vector2(1.0f, -1.0f),
            new Vector2(1.0f, 1.0f),
            new Vector2(-1.0f, 1.0f)
        };

        var path2 = new Vector2[]
        {
            new Vector2(1.5f, -2.5f),
            new Vector2(2.5f, -2.5f),
            new Vector2(2.5f, -1.5f),
            new Vector2(1.5f, -1.5f)
        };

        collider.pathCount = 3;

        collider.SetPath(0, path0);
        collider.SetPath(1, path1);
        collider.SetPath(2, path2);  
    }
}

The square regions defined by path1 and path2 define empty space inside path0. You can configure these paths easily using your own script that you add to GameObjects replacing the use of colliders to define them.

Additionally, you can use a CompositeCollider2D on the PolygonCollider2D and set its geometry mode to Outlines if you require like this:

2 Likes

I was thinking about using PolygonCollider2D to work around, the infomation and tips are so helpful, thanks a lot!

1 Like