0
votes

I am attempting to use Tilemaps in Unity, and I ran into a strange result. I am doing grid-based movement along the tiles, so I have two TileMaps. One is the base that has the ground, the second is a "Collision" TileMap that has trees and rocks and other things my characters might run into.

I wanted to use HasTile to check the Collision TileMap instead of bothering with colliders, since I am doing Grid-Based movement, and partial results would be wasted. Only, I couldn't seem to get my code to recognize tiles in the Collider TileMap.

I dug in a bit and wrote this snippet of code

    Tilemap bas = GameObject.FindGameObjectWithTag("Ground").GetComponent<Tilemap>();
    Tilemap ter = GameObject.FindGameObjectWithTag("Terrain").GetComponent<Tilemap>();
    Vector3Int t1 = new Vector3Int(1, 1, 0);
    Vector3Int t2 = new Vector3Int(2, 1, 0);
    Vector3Int t3 = new Vector3Int(1, 2, 0);
    Vector3Int t4 = new Vector3Int(2, 2, 0);
    Debug.Log("Ground: " + bas.name);
    Debug.Log("Terrain: " + ter.name);
    Debug.Log("1, 1 has a ground tile: " + bas.HasTile(t1));
    Debug.Log("2, 1 has a ground tile: " + bas.HasTile(t2));
    Debug.Log("1, 2 has a terrain tile: " + ter.HasTile(t3));
    Debug.Log("2, 2 has a terrain tile: " + ter.HasTile(t4));`

Rough, I know, but I just wanted to test both TileMaps in known conditions to figure out if I was using HasTile() correctly.

I set it up so like this:

I deleted the ground tile from (1,1) and added a tree to the Collision TileMap in (2,2)

I deleted the ground tile from (1,1) and added a tree to the Collision TileMap in (2,2)

The results were surprising! It read my CollisionMap correctly, false for (1,2) and true for (2,2), and it read GroundTile (2,1) correctly as true, but it also read GroundTile (1,1) as true!!!

Do I need to do something to update it before it recognizes that a tile has been erased? Is this a bug? Can I not trust HasTile()?

1
I realized that I had not updated to the newest version of unity, so I tried updating. Unfortunately, the problem still happens.Lame Brain

1 Answers

0
votes

Ok, I found it! It took me WAAAY too long, but I found the answer.

Basically, I started with the assumption that the coordinates of my character were the same as the coordinates of the TileMap. This is wrong.

So the answer was to change my code to this:

Vector3Int t1 = new Vector3Int(1, 1, 0); t1 = bas.WorldToCell(t1);
Vector3Int t2 = new Vector3Int(2, 1, 0); t2 = bas.WorldToCell(t2);
Vector3Int t3 = new Vector3Int(1, 2, 0); t3 = ter.WorldToCell(t3);
Vector3Int t4 = new Vector3Int(2, 2, 0); t4 = ter.WorldToCell(t4);

and now it works great!