I am trying to dynamically remove tiles from a Tilemap if they touch a shovel. This is the code which is appended to the Tilemap:
private void OnCollisionEnter2D(Collision2D collision) {
if (collision.gameObject.GetComponent<Shovel>() != null) {
ContactPoint2D[] contacts = new ContactPoint2D[10];
collision.GetContacts(contacts);
foreach (ContactPoint2D hit in contacts) {
tilemap.SetTile(tilemap.WorldToCell(hit.point), null);
//Instantiate(debugDot, hit.point, Quaternion.identity);
}
}
}
This works mostly, but sometimes it does not as you can see in the following picture:
The shovel just lays on a tile instead of destroying it. For some reason the OnCollisionEnter2D method is not called although obviously a collision has happened (otherwise the shovel would fall down).
The red dots in the image are for debugging and mark all positions where a collision has occured according to OnCollisionEnter2D.
Does anybody know how I can solve my problem? Thanks in advance!
I tried to test this by increasing the size of the array to 100 and then I printed a warning if the point of last ContactPoint2D of the array does not equal zero (which means that the array is fully filled). It still happens that the shovel lays on tiles without destroying it although the array is not fully filled.