首页 > 解决方案 > Unity 2019.3.9f1:使用TileMap.HasTile(),这正常吗?

问题描述

我正在尝试在 Unity 中使用 Tilemaps,但遇到了一个奇怪的结果。我正在沿着瓷砖进行基于网格的移动,所以我有两个 TileMap。一个是有地面的基地,第二个是“碰撞”TileMap,里面有树木和岩石以及我的角色可能遇到的其他东西。

我想使用 HasTile 来检查 Collision TileMap 而不是打扰对撞机,因为我正在做基于网格的移动,部分结果会被浪费。只是,我似乎无法让我的代码识别 Collider TileMap 中的瓷砖。

我挖了一点,写了这段代码

    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));`

粗糙,我知道,但我只是想在已知条件下测试两个 TileMap,以确定我是否正确使用了 HasTile()。

我是这样设置的:

我从 (1,1) 中删除了地砖,并在 (2,2) 中的 Collision TileMap 中添加了一棵树

我从 (1,1) 中删除了地砖,并在 (2,2) 中的 Collision TileMap 中添加了一棵树

结果令人惊讶!它正确读取了我的 CollisionMap,(1,2) 为 false,(2,2) 为 true,它正确读取 GroundTile (2,1) 为 true,但它也将 GroundTile (1,1) 读取为 true!

在它识别出瓷砖已被擦除之前,我是否需要对其进行更新?这是一个错误吗?我可以不信任 HasTile() 吗?

标签: unity3dtile

解决方案


好的,我找到了!我花了太长时间,但我找到了答案。

基本上,我首先假设我的角色坐标与 TileMap 的坐标相同。这是错误的。

所以答案是将我的代码更改为:

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);

现在效果很好!


推荐阅读