Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. We have updated the language to the Editor Terms based on feedback from our employees and community. Learn more.
    Dismiss Notice

How to detect if a tilemap is overlapping another tilemap

Discussion in 'Scripting' started by Jqob, Apr 21, 2019.

  1. Jqob

    Jqob

    Joined:
    Dec 20, 2018
    Posts:
    34
    I have multiple tilemaps instantiated next to each other. I want to check if a tilemap is overlapping a different tilemap. Specifically they're rooms, with wall tiles having collision enabled and floor tiles - disabled.

    I want to check if one tilemaps wall-tiles are overlapping a different tilemaps floor-tiles...

    So far I've gotten this to get collision:

    Collider2D[] collidingObjects = new Collider2D[5];
    ContactFilter2D contactFilter = new ContactFilter2D();
    tilemap.GetComponent<TilemapCollider2D>().OverlapCollider(contactFilter, collidingObjects)


    But with this I can only find out if Im colliding with a tilemap, but not necessarily overlapping. See, my rooms are touching each other...
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    You can query some information like .cellBounds or .localBounds, and there's probably other information you can get as well. Here are the docs:

    https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.html

    If your tilemap shapes are not rectangular, at least you can use above for a gross check, then iterate down on individual tiles and see if they overlap. Keep in mind due to floating point imprecision, a tilemap that just barely "kisses" another tilemap (directly adjacent) may mathematically overlap with a simple rectangular check, so you might want to check if it overlaps by more than a certain amount, like more than half a tile.
     
  3. Jqob

    Jqob

    Joined:
    Dec 20, 2018
    Posts:
    34
    How do I check overlapping of individual tiles? My rooms have different sizes and placement.
     
  4. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    36,971
    I would just iterate one tilemap and do per-tile rectangle-intersection checks against all the other tiles in the other tilemaps that intersect. You know how many tiles across and down and you know the size of the tiles, so producing the rects is just a little bit of math.

    The good news is you only have to consider the case where the gross outer rectangles have intersected, otherwise by geometric definition, none of the inner rectangles could be intersecting.