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. Dismiss Notice

Best Way To Detect Collision Between Tile and Other Object and Get Tile Position

Discussion in '2D' started by Shmoji, Jan 23, 2019.

  1. Shmoji

    Shmoji

    Joined:
    Nov 16, 2017
    Posts:
    14

    Vector3Int coordinate = grid.WorldToCell(toolColliderPosition);
    cottonMap.SetTile(coordinate, null); // Remove tile


    Using the SetTile method above can remove a tile and I have successfully observed that. However, I have a rotating object in my game with a collider, but it cannot seem to get the correct position for the tiles.

    All I want is when the rotating object collides with a tile, the tile should be deleted.

    In a tilemap, you only have one TilemapCollider2D object, but you can still remove individual tiles. I just do not know how to do it accurately. So, in order to remove a tile, I first need the Vector3 that corresponds to the grid cell it is at. I thought I could use WorldToCell to help me with that, but it is not accurate at all.

    What would you do? Any ideas?
     
    Shorely likes this.
  2. ChuanXin

    ChuanXin

    Unity Technologies

    Joined:
    Apr 7, 2015
    Posts:
    1,068
    This was used in a TilemapCollider2D demo here from 2d-techdemos.

    Code (CSharp):
    1.  
    2. void OnCollisionEnter2D(Collision2D collision)
    3. {
    4.     Vector3 hitPosition = Vector3.zero;
    5.     foreach (ContactPoint2D hit in collision.contacts)
    6.     {
    7.         hitPosition.x = hit.point.x - 0.01f * hit.normal.x;
    8.         hitPosition.y = hit.point.y - 0.01f * hit.normal.y;
    9.         tilemap.SetTile(tilemap.WorldToCell(hitPosition), null);
    10.     }
    11. }
    12.  
    As the collision points are generally on the edge of each Tile, extending the collision normal will give a better result.
     
  3. ChuanXin

    ChuanXin

    Unity Technologies

    Joined:
    Apr 7, 2015
    Posts:
    1,068
    Certainly, that works. However, with a large number of Tiles, you would want to composite and reduce the number of collider shapes, especially if they form a contiguous area.
     
  4. Durium

    Durium

    Joined:
    Feb 1, 2020
    Posts:
    30

    Hello! Contacts can no longer be used, how can we achieve this ? :)
     
  5. ChuanXin

    ChuanXin

    Unity Technologies

    Joined:
    Apr 7, 2015
    Posts:
    1,068
    MiroBrodlova and spark-man like this.
  6. Ziplock9000

    Ziplock9000

    Joined:
    Jan 26, 2016
    Posts:
    360
    Can we get a code example within an OnCollisionEnter2D event?
     
    MiroBrodlova likes this.