主要函数是bounds.IntersectRay
if (Input.GetMouseButtonDown(0) && (!GetComponent<Collider>() || !GetComponent<Collider>().enabled))
{
var ray = _camera.ScreenPointToRay(Input.mousePosition);
foreach (var meshRenderer in gameObject.GetComponentsInChildren<Renderer>(true))
{
if (meshRenderer.bounds.IntersectRay(ray))
{
_mouseButtonDownTime = Time.time;
onPointerDown?.Invoke(gameObject, new PointerEventData(EventSystem.current));
break;
}
}
}else if (Input.GetMouseButtonUp(0) && (!GetComponent<Collider>() || !GetComponent<Collider>().enabled))
{
var ray = _camera.ScreenPointToRay(Input.mousePosition);
foreach (var meshRenderer in gameObject.GetComponentsInChildren<Renderer>(true))
{
if (meshRenderer.bounds.IntersectRay(ray))
{
if (Time.time - _mouseButtonDownTime <= PointerClickTimeout)
{
onPointerClick?.Invoke(gameObject, new PointerEventData(EventSystem.current));
}
onPointerUp?.Invoke(gameObject, new PointerEventData(EventSystem.current));
break;
}
}
}
该代码段实现了一个在Unity中检测鼠标点击和释放的逻辑,使用Camera的ScreenPointToRay方法将鼠标位置转换为射线,然后遍历所有子物体的Renderer,检查Bounds是否与射线相交。如果相交,则触发相应的点击和释放事件。点击时间和释放时间之间的间隔用于判断是否为有效点击。

1万+

被折叠的 条评论
为什么被折叠?



