我正在尝试突出显示由鼠标悬停的瓷砖。这是我的代码:
void Update ()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit))
{
Vector3 point = hit.point;
Vector2Int gridPoint = Geometry.GridFromPoint(point);
tileHighlight.SetActive(true);
tileHighlight.transform.position = Geometry.PointFromGrid(gridPoint);
if (Input.GetMouseButtonDown(0))
{
// ...
编辑:
public class Geometry
{
static public Vector3 PointFromGrid(Vector2Int gridPoint)
{
float x = -3.5f + 1.0f * gridPoint.x;
float z = -3.5f + 1.0f * gridPoint.y;
return new Vector3(x, 0, z);
}
static public Vector2Int GridPoint(int col, int row)
{
return new Vector2Int(col, row);
}
static public Vector2Int GridFromPoint(Vector3 point)
{
int col = Mathf.FloorToInt(4.0f + point.x);
int row = Mathf.FloorToInt(4.0f + point.z);
return new Vector2Int(col, row);
}
}
光标对象不在鼠标下面,我如何修复和对齐它?
您要将它转换为网格点,然后从网格转换为点。我们也没有看到您的转换代码。
我建议尝试这样做,至少在调试时是这样:
tileHighlight.SetActive(true);
tileHighlight.transform.position = hit.point;
编辑:
我假设你的网格是缩放的,所以它不适合计算的位置。您可以尝试以下代码:
public int grid_scale = 2; // play with this in the inspector
Vector3 snapped = Vector3.zero;
snapped.x = Mathf.Round(hit.point.x / grid_scale) * grid_scale;
snapped.z = Mathf.Round(hit.point.z / grid_scale) * grid_scale;
您可能需要添加一个偏移量来使它以瓷砖为中心。