首页 > 解决方案 > 光线投射和 OnMouseOver 之间的精度差异

问题描述

我对我在 Unity3D 项目中看到的内容感到非常惊讶,并且想知道是否有人有解释,因为我在谷歌上查找后没有找到解释。

所以我有一个项目,我在其中实例化多个对象,这些对象基本上是立方体,它们的碰撞器(未触发)以及我想知道鼠标是否在其中一个上。所以我附上了一个来自统一文档的非常基本的脚本:

void OnMouseEnter()
{
    Debug.Log("enter block " + this.name); 
    // Change the color of the GameObject to red when the mouse is over GameObject
    m_Renderer.material.color = m_MouseOverColor;
}

void OnMouseOver()
{
    Debug.Log("over block " + this.name); 
    // Change the color of the GameObject to red when the mouse is over GameObject
    m_Renderer.material.color = m_MouseOverColor;
}

void OnMouseExit()
{
    Debug.Log("exit block " + this.name);
    // Reset the color of the GameObject back to normal
    m_Renderer.material.color = m_OriginalColor;
}

而且我似乎没有看到任何结果。在寻找选项时,我将碰撞器框缩放到更大并且可以获得一些结果,但它们并不精确,鼠标需要稍微放在立方体的一侧才能工作。它看起来像是由对撞机的大小引起的透视效果,这对于最终用户来说会很烦人。

所以我尝试在附加到相机的脚本中使用简单的光线投射测试:

Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, 100000000, LayerMask.GetMask("TrackPartEnd")))
{
    Debug.DrawRay(ray.origin, ray.direction * 100000000, Color.blue, 3);
    myCursorObject.transform.position = hit.point;
}
else
{
    if (Physics.Raycast(ray, out hit, 100000000, LayerMask.GetMask("Floor")))
    {
       Debug.DrawRay(ray.origin, ray.direction * 100000000, Color.green, 3);
       myCursorObject.transform.position = hit.point;
    }
    else
    {
       Debug.DrawRay(ray.origin, ray.direction * 100000000, Color.red, 3);
    }
}

有了这个,我得到了一个非常好的结果,它快速且非常精确。

但是我没有找到任何解释为什么?据我所知,OnMouseOver 也使用光线投射。我已经仔细检查过,也没有看到任何阻挡光线的东西。有人有解释吗?

标签: unity3d

解决方案


推荐阅读