Unity3D 等距平铺地图的鼠标事件

Pat*_*hon 3 c# 2d tile unity-game-engine isometric

我一直在阅读 Unity3D 中新的图块地图系统。我已经成功地设置了网格 -> 图块地图并设置了图块调色板。然而现在我正在努力寻找最新的教程来处理这个新的图块地图系统的鼠标事件。

我试图在鼠标悬停在图块上时设置突出显示,并且如果单击图块,我希望能够触发脚本和其他事件。然而,在线可用的教程并没有讨论图块地图系统的鼠标事件,也很少讨论等距图块地图。

是否有任何好的最新教程来处理等距平铺地图上的鼠标事件?即使是一个简单的教程,显示图块上的悬停效果以及单击图块时的“图块 xy 的 hello world”,也将是我真正需要的。

这是我到目前为止所拥有的:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class MouseManager : MonoBehaviour
{
    void Update()
    {
        Vector3 clickPosition = Vector3.one;
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        RaycastHit hit;
        if(Physics.Raycast(ray, out hit))
        {
            clickPosition = hit.point;
        }
        Debug.Log(clickPosition);
    }
}
Run Code Online (Sandbox Code Playgroud)

Hum*_*tes 5

这应该可以帮助您开始:

using UnityEngine;
using UnityEngine.Tilemaps;

public class Test : MonoBehaviour {

   //You need references to to the Grid and the Tilemap
   Tilemap tm;
   Grid gd;

   void Start() {
       //This is probably not the best way to get references to
       //these objects but it works for this example
       gd = FindObjectOfType<Grid>();
       tm = FindObjectOfType<Tilemap>();
   }

   void Update() {

       if (Input.GetMouseButtonDown(0)) {
           Vector3 pos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
           Vector3Int posInt = gd.LocalToCell(pos);

           //Shows the cell reference for the grid
           Debug.Log(posInt);

           // Shows the name of the tile at the specified coordinates
           Debug.Log(tm.GetTile(posInt).name);
       }
   }
}
Run Code Online (Sandbox Code Playgroud)

简而言之,获取网格和图块地图的参考。使用 ScreenToWorldPoint(Input.mousePosition) 查找局部坐标。调用网格对象的 LocalToCell 方法将本地坐标 (Vector3) 转换为单元坐标 (Vector3Int)。将单元格坐标传递给 Tilemap 对象的 GetTile 方法以获取 Tile(然后使用与 Tile 类关联的方法进行您想要进行的任何更改)。

在这个例子中,我只是将上面的脚本附加到世界中的一个空游戏对象上。相反,将其附加到网格可能是有意义的。尽管如此,一般逻辑仍然相同。