我对我在Unity3D项目中看到的内容感到非常惊讶,并想知道是否有人解释过,因为在Google上找到它后我找不到它。
因此,我有一个项目,其中实例化多个对象(基本上是多维数据集)及其对撞机(未触发),并且我想知道鼠标是否位于其中之一上。 因此,我附上了一个非常基本的脚本,该脚本取自统一文档:
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也使用raycast。我仔细检查过,也看不到任何阻挡光线的东西。 有人有解释吗?