I'm using Unity to create a 2D platformer game. I ran into an issue I was hoping someone could help me with. I'm using OnCollisionEnter2D() to detect when the player gameobject touches the ground, which is a tilemap. At the most basic implementation, it looks like this:
private void OnCollisionEnter2D(Collision2D collision) {
Debug.Log("Tile collision");
var map = collision.collider.GetComponent<Tilemap>();
var grid = map.layoutGrid;
// Find the coordinates of the tile we hit.
var contact = collision.GetContact(0);
Vector3 contactPoint = contact.point - 0.05f * contact.normal;
Vector3 gridPosition = grid.transform.InverseTransformPoint(contactPoint);
Vector3Int cell = grid.LocalToCell(gridPosition);
// Extract the tile asset at that location.
var tile = map.GetTile(cell);
if(tile == null)
return; // No valid tile! Abort!
// Do something when a new tile is hit
// TODO: Place function here
}
When I run my game, the console displays "tile collision" whenever I jump and then touch a tilemap surface. The console message will not display again until I leave whatever surface I'm on and touch it again. Although this is close to what I want, it's not exactly what I'm trying to achieve.
I'd like to be able to display the message every time the player touches another tile, even if its the same tile the player was previously touching. I'm not entirely sure how to implement this, though. Does anyone have any pointers that might help me achieve my desired outcome?
OnCollisionStay2D
? Also, there's no engine called "Unity2D" — it's just Unity, no matter what mix of dimensions you're using. \$\endgroup\$