Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

Test for potential collision (2D)

Discussion in 'Scripting' started by Bankler, Mar 30, 2015.

  1. Bankler

    Bankler

    Joined:
    Apr 10, 2012
    Posts:
    66
    I have an hierarchy (h) consisting of a couple of different collider2D:s. h1 is the parent.
    h1 is a BoxCollider2D
    h2 is a BoxCollider2D
    h3 is a PolygonCollider2D

    I would like to implement a function that can take the hierarchy h and a positition, and then have it determine if the hierarchy would fit at that position (return true), or if any of its colliders would intersect (return false).

    (See attached image for more detailed explanation)

    My approach so far has been to recursively go through the nodes in the hierarchy, and then calculate the top-left/bottom-right corners on each child's "would-be" position, and test with Physics2D.OverlapAreaAll on each one. This feels very fiddly, also it won't really work with polygon colliders.

    Any suggestions on better approaches? I'm very grateful for any push in the right direction. Cheers! ;)
    CollisionTest.png
     
  2. Brominion

    Brominion

    Joined:
    Sep 30, 2012
    Posts:
    48
    I think you could try creating an invisible copy of the objects (essentially only the colliders), place those, and check if they intersect anything.
     
  3. Bankler

    Bankler

    Joined:
    Apr 10, 2012
    Posts:
    66
    Thanks! Sounds interesting. I would have to wait until the next physics update before I know if there is a collision though. Which in turn would probably require me to register a callback on the "copy" and listen to that (so it can tell me if it was a collision, when it knows), adding some complexity. Seems like the same goes even if I'd use Collider2D.IsTouching(). Seems sort of reasonable though I guess.

    Any other suggestions?