我刚刚开始习惯于使用Unity的新tilemap工具(UnityEngine.Tilemaps)。
我遇到的一个问题是我不知道如何通过脚本获取放置的图块的x,y坐标。我正在尝试将脚本中的tilemap上的scriptableObject移动到播放器单击的新位置,但是我不知道如何获取所单击的tile位置的坐标。Tile类似乎没有任何position属性(Tile对其位置一无所知),因此Tilemap必须具有答案。我无法在Unity文档中找到有关如何在Tilemap中获取所选图块的Vector3坐标的任何信息。
如果您有权访问Tile实例,则可以使用其变换(或单击时发出的光线冲击)来获取其世界位置,然后通过组件的WorldToCell方法来获取切片坐标Grid(请参阅文档)。
编辑:
Unity似乎不实例化图块,而是仅使用一个图块对象来管理该类型的所有图块,但我没有意识到。
要获得正确的位置,您必须自己计算。这是一个示例,该示例说明了当网格位于z = 0的xy平面时如何在鼠标光标处获得平铺位置
// get the grid by GetComponent or saving it as public field
Grid grid;
// save the camera as public field if you using not the main camera
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
// get the collision point of the ray with the z = 0 plane
Vector3 worldPoint = ray.GetPoint(-ray.origin.z / ray.direction.z);
Vector3Int position = grid.WorldToCell(worldPoint);
Run Code Online (Sandbox Code Playgroud)
我找不到通过鼠标单击获取网格位置的方法,因此我使用 Raycast to Vector3,然后WorldToCell按照 Shirotha 的建议通过网格组件的方法将其转换为坐标。这允许我将所选内容移动GameObject到新位置。
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
另一方面,我知道如何获取网格位置,但现在如何查询它。我需要从 Grid 获取 GridSelection 静态对象,然后获取其位置。
| 归档时间: |
|
| 查看次数: |
9055 次 |
| 最近记录: |