2D射线检测
public List<RaycastResult> click2DItem()
{
PointerEventData pointerEventData = new PointerEventData(EventSystem.current);
pointerEventData.position = Input.mousePosition;
GraphicRaycaster gr = UIcanvas.GetComponent<GraphicRaycaster>();
List<RaycastResult> results = new List<RaycastResult>();
gr.Raycast(pointerEventData, results);
return results;
}
通过下列代码块调用上列方法会返回鼠标点击下去的第一个物体
List<RaycastResult> results = new List<RaycastResult>();
results = click2DItem();
GameObject item = results[0].gameObject;
3D射线检测
public RaycastHit RayHit()
{
Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
RaycastHit hit;
if (Physics.Raycast(ray, out hit, Mathf.Infinity))
{
Debug.DrawLine(ray.origin, hit.point, Color.red);
}
return hit;
}
通过下列代码块调用上列方法会返回鼠标点击下去由摄像机发出射线碰撞到场景中的第一个物体,需要被射线检测的物体需要加碰撞体collider组件。
GameObject obj = RayHit().collider.gameObject;
|