如何在tilemap中获取瓷砖的x,y坐标位置? [英] How can I get the x,y coordinate location of a tile in the tilemap?

查看:2058
本文介绍了如何在tilemap中获取瓷砖的x,y坐标位置?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚开始习惯于使用Unity的新tilemap工具(UnityEngine.Tilemaps).

I have just started getting used to using Unity's new tilemap tool (UnityEngine.Tilemaps).

我遇到的一个问题是我不知道如何通过脚本获取放置的图块的x,y坐标.我正在尝试将脚本中的tilemap上的scriptableObject移动到玩家单击的新位置,但是我不知道如何获取所单击的tile位置的坐标. Tile类似乎没有任何position属性(Tile对其位置一无所知),因此Tilemap必须具有答案.我无法在Unity文档中找到有关如何在Tilemap中获取所选图块的Vector3坐标的任何信息.

One issue I am having is that I don't know how to get the x,y coordinates of a placed tile via script. I am trying to move a scriptableObject on the tilemap in script to a new location that the player clicks, but I don't know how to get the coordinates of the clicked tile location. There doesn't seem to be any position property for the Tile class (the Tile knows nothing about its location), so the Tilemap must have the answer. I was not able to find anything in the Unity documentation for how to get the Vector3 coordinates for a selected tile in the Tilemap.

推荐答案

我找不到通过鼠标单击来获取网格位置的方法,因此我使用了Raycast到Vector3,然后将其转换为坐标根据Shirotha的建议通过Grid组件的WorldToCell方法.这使我可以将所选的GameObject移动到新位置.

I couldn't find a way to get the Grid's position from mouse click, so instead I used a Raycast to Vector3, and then converted that to coordinates via the WorldToCell method of the Grid component as per Shirotha's suggestion. This allows me to move the selected GameObject to a new position.

public class ClickableTile : MonoBehaviour
{
    public NormalTile normalTile;
    public Player selectedUnit;

    private void OnMouseUp()
    {
        // left click - get info from selected tile
        if (Input.GetMouseButtonUp(0))
        {
            // get mouse click's position in 2d plane
            Vector3 pz = Camera.main.ScreenToWorldPoint(Input.mousePosition);
            pz.z = 0;

            // convert mouse click's position to Grid position
            GridLayout gridLayout = transform.parent.GetComponentInParent<GridLayout>();
            Vector3Int cellPosition = gridLayout.WorldToCell(pz);

            // set selectedUnit to clicked location on grid
            selectedUnit.setLocation(cellPosition);
            Debug.Log(cellPosition);
        }
    }
}

顺便说一句,我知道如何获取Grid的位置,但是现在知道如何查询它.我需要从Grid获取GridSelection静态对象,然后获取其位置.

On an aside, I know how to get the Grid location, but now how to query it. I need to get the GridSelection static object from Grid, and then get its position.

这篇关于如何在tilemap中获取瓷砖的x,y坐标位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆