获取网格单元的中心 - Unity

4
我正在使用Unity开发一个等轴投影游戏,需要知道单元格在世界坐标系中的中心点。我使用了tilemap的GetCellCenterWorld()方法,但是它返回了错误的结果。我期望得到的是这里的单元格中心(基本上是逻辑中心),但是Unity返回的是这里的结果(单元格的顶部顶点?)。我认为这可能与精灵的枢轴点(现在设置为其顶部中心)或tilemap属性中单元格锚点的设置有关(我将其设置为(1,1))。
以下是我用于“选择”图块的代码:
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);
    }
}

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

3个回答

3

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

如果有人遇到相同的问题,这是我解决它的方法:

  1. 将精灵的中心点设置为您希望单元格中心点位于的位置(在我的情况下,是草坪部分的中心)
  2. 将瓦片锚点设置回(0.5,0.5)
  3. 正常使用GetCellCenterWorld() 方法

我在问题中发布的代码现在运行得很好。


1
[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


0

不幸的是,这给了我瓷砖地图的中心而不是实际瓷砖的中心 :/ - thelukaszns

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接