c# - Unity3D 等距瓦片 map 的鼠标事件

标签 c# unity3d 2d tile isometric

我一直在阅读 Unity3D 中的新瓦片 map 系统。我已经设法达到设置网格 -> 瓷砖 map 和设置瓷砖调色板的地步。然而,现在我正在努力寻找最新的教程来处理这个新的瓦片 map 系统的鼠标事件。

我试图在鼠标悬停在图 block 上时设置高亮显示,如果单击图 block 我希望能够触发脚本和其他事件。然而,可用的在线教程不会涉及瓦片 map 系统的鼠标事件,也很少讨论等距瓦片 map 。

是否有关于在等距瓦片 map 上处理鼠标事件的最新教程?即使是显示磁贴上的悬停效果和单击磁贴时“来自磁贴 x.y 的 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);
    }
}

最佳答案

这应该让你开始:

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);
       }
   }
}

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

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

关于c# - Unity3D 等距瓦片 map 的鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54357827/

相关文章:

unity-game-engine - 忽略特定情况下的碰撞,同时仍将其用作触发器

python - 如何将具有对象 dtype 的 Numpy 二维数组转换为常规的二维 float 组

c# - 如何正确实现 Parallel.For 以获得正确的状态?

c# - 在生产源代码中将 Entity Framework 日志记录设置为调试窗口是否可以?

c# - 通过依赖注入(inject)在主窗体中初始化接口(interface)

algorithm - 检测体素或体素组是否仍连接到对象的其余部分

C# Unity 3D - 有没有办法制作自定义光线转换形状?

c# - 选择 ID 在 int 数组中的实体 - WCF 数据服务,LINQ

c# - 单位圆计算

c - 二维实时绘图与 C