获取网格单元的中心 - 统一

Getting the center of a grid's cell - unity

我正在使用 Unity 开发等距游戏,我需要知道世界坐标中单元格的中心。我正在使用 tilemap 的 GetCellCenterWorld() 方法,但它给了我不好的结果。 Here is what I expect to be the centre of the cell (basically the logical centre), but here 是 Unity 返回的(单元格的顶部顶点?)。我相信它与 sprite 的枢轴点(现在设置为它的顶部中心)或 tilemap 属性中的单元格锚点(我将其设置为 (1,1))有关。

这是我用来“select”磁贴的代码:

public class GridSelection : MonoBehaviour
{
    public Tilemap tilemap;
    public Transform selector;

    void Update()
    {
        Vector3 worldPos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        worldPos.z = 0;

        Vector3Int tilemapPos = tilemap.WorldToCell(worldPos);
        selector.position = tilemap.GetCellCenterWorld(tilemapPos);
    }
}

如何获取单元格的实际中点?

尝试tilemap.cellBounds.center https://docs.unity3d.com/ScriptReference/Tilemaps.Tilemap.html

好的,我想我找到问题所在了。

如果有人遇到同样的问题,我是这样解决的:

  1. 将 sprite 轴心点设置到您希望单元格中间所在的位置(在我的例子中,草地部分的中心)
  2. 将图块锚点设置回 (0.5, 0.5)
  3. 正常使用GetCellCenterWorld()方法

我在问题中发布的代码现在可以正常工作了。

[SerializeField] private Tilemap map;
private Camera camera;
[SerializeField] private Transform playerTransform;

void Start(){
    camera = Camera.main;
}

// Update is called once per frame
void Update(){
    if (Input.GetMouseButtonDown(0)){
        var worldPos = camera.ScreenToWorldPoint(Input.mousePosition);
        Vector3Int tilemapPos = map.WorldToCell(worldPos);
        playerTransform.position = map.CellToWorld(tilemapPos);
        Debug.Log(tilemapPos);
    }
}

playerTransform.position = map.CellToWorld(clickedCellPosition);

只需将其转换回来并提供 tilemapPos