Player's gameobject doesn't detect collided tiles

SImple setup: suppose that the player controls a Gameobject, with a Rigidbody2d and a BoxCollider2D (IsTrigger disabled) and detects collision. A Tilemap contains 30 tiles, it contains a Tilemap Collider 2d (also IsTrigger disabled). The player moves his gameobject using rigidbody, not via transform. Collsion with the tilemap is fine. However, it seems that I can’t find out the specific tile at the collision point.

My simple code is as follows:

 private  void OnCollisionEnter2D(Collision2D collision)
{
   Debug.Log("collided");
   Vector3 contactPoint = collision.GetContact(0).point;
   Vector3Int cellPosition = collision.gameObject.GetComponent<Tilemap().WorldToCell(contactPoint);

   TileBase touchedTile = collision.gameObject.GetComponent<Tilemap>().GetTile(cellPosition);

   if (touchedTile != null)
   {
       Debug.Log("Collided with tile at {cellPosition} with tile name: {touchedTile.name}");
   }
 }

Like collision with the tilemap exists, but I wanted to find specific tile, while my touchedTile is null (in fact, sometimes it returns my desired tile, sometimes not). What’s wrong there in this code?

The contact point is not always going to be inside the collider, but very likely somewhere between your player’s collider and the tilemap collider.

I’ve been meaning to play around with a solution for this for my current project, but I imagine you would need to use the normal of the contact to test a position further into the collider.