Unity3D等距地图的鼠标事件

3
我一直在研究Unity3D中的新瓷砖地图系统。我已经成功设置了网格->瓷砖地图并设置了瓷砖调色板。但现在我正在努力寻找处理此新瓷砖地图系统的鼠标事件的最新教程。
我试图在鼠标悬停在瓷砖上时设置高亮显示,如果单击瓷砖,我想能够触发脚本和其他事件。然而,网上提供的教程没有涉及到瓷砖地图系统的鼠标事件,很少有关于等距瓷砖地图的讨论。
是否有任何好的最新教程来处理等距瓷砖地图上的鼠标事件?即使是一个简单的教程,展示瓷砖上的悬停效果和当瓷砖被点击时的"hello world from tile x.y",都足以让我开始。
这是我目前为止所拥有的:
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);
    }
}
2个回答

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

简单来说,获取网格和瓦片地图的引用。使用ScreenToWorldPoint(Input.mousePosition)找到本地坐标。调用网格对象的LocalToCell方法将您的本地坐标(Vector3)转换为单元格坐标(Vector3Int)。将单元格坐标传递给Tilemap对象的GetTile方法以获取瓦片(然后使用与Tile类关联的方法进行任何所需更改)。
在此示例中,我只是将上述脚本附加到世界中的空GameObject上。 然而,将其附加到网格上可能更有意义。不过,总体逻辑仍然相同。

3
这是一个与HumanWrites不同的版本。它不需要对网格进行引用,而且mousePos被声明为Vector2,而不是Vector3——这将避免在2D中工作时出现问题。最初的回答。
using UnityEngine;
using UnityEngine.Tilemaps;

public class MouseManager : MonoBehaviour
{

private Tilemap tilemap;

void Start()
{
    tilemap = FindObjectOfType<Tilemap>();
}

void Update()
{
    if (Input.GetMouseButtonDown(0))
    {
        Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
        Vector3Int gridPos = tilemap.WorldToCell(mousePos);

        if (tilemap.HasTile(gridPos))
            Debug.Log("Hello World from " + gridPos);
    }
}

}

我们所提到的“tilemap”是你场景中的一个gameObject。你可能已经将其重命名为其他名称,但它应该是“Grid”对象的子对象。enter image description here最初的回答

在这段代码中,.Find("Tilemap") 是查找组件的名称还是标签? - Patrick W. McMahon

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