Unity Tilemap Collision Detection - Tue, Jan 25, 2022
While working on a 2D platformer on Unity, I decided to implement ladders with tile maps with a specific layer designated for ladders. I added a Tilemap Collider 2D component to it with Is Trigger set to true
. The plan was to detect the overlap of player and a ladder tile using Unity’s OnTriggerEnter2D(Collider2D)
and OnTriggerExit2D(Collider2D)
methods.
The Collider2D
object refer to the collider attached to the tilemap. I thought collider2D.transform
or .bounds
properties would return the position of the actual overlapping tile, but I was wrong.
In the end I solved the problem using a different approach:
1, Get the Tilemap
object for the ladder,
2, Use the .WorldToCell(Vector3)
method of the tilemap to get the discrete cell position of the tile that overlaps with the passed position, in this case player’s transform.position
.
3, The center of the overlapping tile would be the world position of the tile map + the cell position + half of tileMap.cellSize
.
_
foreach (var collision in Colliders.Where(x => x.gameObject.layer == LadderLayerId))
{
IsLadder = true;
var tileMap = collision.GetComponent<Tilemap>();
var cellPos = tileMap.WorldToCell(transform.position);
var tile = tileMap.GetTile(cellPos);
if (tile != null)
LadderCenter = tileMap.transform.position + cellPos + tileMap.cellSize * 0.5f;
}