鼠标指针的点击距离

时间:2021-05-16 17:03:54

标签: c# mouse offset

我想用几何脚本中的 PointFromGrid 函数使网格区域更大.. 但是当我想放大网格大小时,鼠标指针不会悬停在选择预制件上 我该如何解决这个问题?

编辑;当我使用 GridFromPoint 函数将其设置为较小的网格大小时,没有问题,但是 放大后无法正确对齐。

 public class Geometry {  

 static public Vector3 PointFromGrid(Vector2Int gridPoint)
 {
    float x = -4.5f + 1.5f * gridPoint.x;
    float z = -4.5f + 1.5f * 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);
 }   

这是选择预制脚本

 void Start()
 {       
    Vector2Int gridPoint = Geometry.GridPoint(0, 0);
    Vector3 point = Geometry.PointFromGrid(gridPoint);
    tileHighlight = Instantiate(tileHighlightPrefab, point, Quaternion.identity, gameObject.transform);
    tileHighlight.SetActive(false);
}

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

enter image description here

enter image description here enter image description here

2 个答案:

答案 0 :(得分:1)

GridFromPoint 似乎与 PointFromGrid 不一致。假设这两种方法执行彼此的逆操作,并假设PointFromGrid是正确的,那么 GridFromPoint 应该计算:

int col = Mathf.FloorToInt((point.x + 4.5f) / 1.5f);
int row = Mathf.FloorToInt((point.z + 4.5f) / 1.5f);

这是一个简单的代数变换。给定 (PointFromGrid):

x = -4.5 + (1.5 * grid.x)

求解grid.x

(0)                    x               = -4.5 + (1.5 * grid.x)
(1) add 4.5:           x + 4.5         =         1.5 * grid.x
(2) divide by 1.5:     (x + 4.5) / 1.5 =               grid.x
(3) swap sides:        grid.x          = (x + 4.5) / 1.5

同样的转换适用于 z


在评论中,您说 -4.5f + 1.5f 是网格大小,而 4.0f 是对齐参数。重要的是要知道这些数字代表什么才能正确地进行转换。 1.5f 必须是网格的行高和列宽,其中 -4.5f 是网格原点和(可能)世界坐标(或可能是某些形状坐标)之间的偏移量。 4.0f 似乎没有意义,因为反向操作必须使用相同的偏移量和网格大小。

答案 1 :(得分:0)

<块引用>
float x = -4.5f + 1.5f * gridPoint.x;
float z = -4.5f + 1.5f * gridPoint.y;

当您在同一个语句中执行算术或乘法/除法时,编译器可能会误解您想要做什么。

在执行涉及不同类型运算的单行数学运算时考虑使用括号。

当你使用括号时,你会阻止编译器看到这个:

float x = -4.5f + 1.5f * gridPoint.x;

并且假设你的意思是:

float x = (-4.5f + 1.5f) * gridPoint.x;

当您很可能希望它像这样工作时

float x = -4.5f + (1.5f * gridPoint.x);

如果没有明确告诉编译器要解释哪个,它有时会选择错误的,并且偏移值会发生奇怪的事情。