Search code examples
c#unity-game-engine2dcollision-detection

Make 2D collider hit only specific 2D colliders without using collision layer mask


In my 2D game, there are some circles randomly placed and some balls.

Each ball has a reference to one of the circles and this circle will apply a force to pull the ball to its center.

However, balls can change their circle. When they do, they fly from the current circle to the new one.

My question is: how to let balls only collide with balls that belong to the same circle? In the moment that a ball changes its circle, I want it to ignore collisions with all the other balls, except the ones which belong to the same new circle.


As I can have a lot of circles, I don't think using collision layers will do the job, so is there a better way?


Solution

  • You could go through Physics2D.IgnoreCollision and store your balls in separate collections.

    Then

    • initially run through them all once and make them ignore all other colliders
    • then every time when entering a circle you run through the balls belonging to that circle and set IgnoreCollision to false for those.
    • once you leave a circle you set them all back to true