- Home /
How to get the position of a Tile my Player collided with using OnTriggerEnter2D?
I am trying to make a simple puzzle game that has the same functionality as Undertale's X O and Triangle puzzle.
This has proved a lot more difficult than I originally thought.
Basically, whenever I walk over an X tile it should change to a O tile, and if I walk over it again it should change into a Triangle tile.
In my head when the player collides with an X tile I would get the position of the collision, check which tile it happened on (I have the collision boxes for the tiles slightly smaller than the size of a full tile) and use SetTile to change the tile.
My problem is the following: if I set the Collider of the Tilemap to be a Trigger and use OnTriggerEnter2D I am unable to get the position of the collision, since I am only able to use the Collider of the other object in the collision, in this case the Player. If I instead don't use it as a Trigger and use OnCollisionEnter2D I am pretty sure I would be able to get the position where the collision happened, however I am no longer able to walk through the X Tile.
This is the code I had to start with for OnTriggerEnter2D, however it's obviously wrong since I didn't know transform.position would return the position of the entire Tilemap and not the individual tile.
public Tilemap tiles;
void OnTriggerEnter2D(Collider2D other)
{
Debug.Log("OnTriggerEnter2D");
Vector3 p = transform.position;
GridLayout gridLayout = transform.parent.GetComponentInParent<GridLayout>();
Vector3Int cellPosition = gridLayout.WorldToCell(p);
Debug.Log(tiles.GetTile(cellPosition));
}