【发布时间】:2016-12-29 11:33:34
【问题描述】:
我试图弄清楚 Graphic.Raycaster 是如何工作的,但文档没有帮助。我想用它从某个位置以某个角度投射光线并击中 UI。另一件事是我不知道如何使它与 UI 交互(拖动、单击等)。我知道这是一个广泛的主题,但我找不到任何关于如何使用它的好的解释,所以我将不胜感激。
【问题讨论】:
-
你读过this 吗?
我试图弄清楚 Graphic.Raycaster 是如何工作的,但文档没有帮助。我想用它从某个位置以某个角度投射光线并击中 UI。另一件事是我不知道如何使它与 UI 交互(拖动、单击等)。我知道这是一个广泛的主题,但我找不到任何关于如何使用它的好的解释,所以我将不胜感激。
【问题讨论】:
来自 Unity 文档:
Graphic Raycaster 用于对 Canvas 进行光线投射。这 Raycaster 查看画布上的所有图形并确定是否有 他们被击中了。
您可以对图形 (UI) 元素使用 EventSystem.RaycastAll 到 raycast。
以下是您的案例的简短示例:
void Update() {
// Example: get controller's current orientation:
Quaternion ori = GvrController.Orientation;
// If you want a vector that points in the direction of the controller
// you can just multiply this quat by Vector3.forward:
Vector3 vector = ori * Vector3.forward;
// ...or you can just change the rotation of some entity on your scene
// (e.g. the player's arm) to match the controller's orientation
playerArmObject.transform.localRotation = ori;
// Example: check if touchpad was just touched
if (GvrController.TouchDown) {
// Do something.
// TouchDown is true for 1 frame after touchpad is touched.
PointerEventData pointerData = new PointerEventData(EventSystem.current);
pointerData.position = Input.mousePosition; // use the position from controller as start of raycast instead of mousePosition.
List<RaycastResult> results = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerData, results);
if (results.Count > 0) {
//WorldUI is my layer name
if (results[0].gameObject.layer == LayerMask.NameToLayer("WorldUI")){
string dbg = "Root Element: {0} \n GrandChild Element: {1}";
Debug.Log(string.Format(dbg, results[results.Count-1].gameObject.name,results[0].gameObject.name));
//Debug.Log("Root Element: "+results[results.Count-1].gameObject.name);
//Debug.Log("GrandChild Element: "+results[0].gameObject.name);
results.Clear();
}
}
}
以上脚本未经本人测试。所以可能会有一些错误。
以下是一些其他参考资料,可帮助您了解更多信息:
希望对你有帮助。
【讨论】:
Input.mousePosition,并检查它是否有效。
Debug.DrawRay(transform.position, vector); 绘制射线时,它正在通过 UI 元素。也许这不起作用,因为vector 被用作位置,而不是方向?
Umair M 当前的建议没有处理射线起源于世界空间并以一定角度传播的事实。
在我看来,即使您的画布在世界空间中,您也无法在世界空间中以某个角度进行 GUI 光线投射。 This page 建议创建一个非渲染摄像机,在 3D 空间中使用您要投射的光线移动它,然后相对于该摄像机进行 GUI 光线投射。我还没有尝试过,但听起来很有希望。
【讨论】: