如何在WorldSpace UI中使用Graphic Raycaster?

时间:2016-08-22 19:49:40

标签: unity3d

我正在试图弄清楚Graphic.Raycaster是如何工作的,但是文档没有帮助。我想用它从某个位置以某个角度投射光线投射并点击UI。另一件事是我不知道如何使它与UI交互(拖动,点击等)。我知道这是一个广泛的主题,但我找不到如何使用它的任何好的解释,所以我将不胜感激任何解释。

2 个答案:

答案 0 :(得分:5)

来自Unity docs:

  

Graphic Raycaster用于对Canvas进行光线投射。该   Raycaster查看画布上的所有Graphics并确定是否有任何   他们被打了。

您可以对图形(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();
     }
   }
}

以上脚本未经我自己测试。所以可能会有一些错误。

以下是一些其他参考资料,可帮助您了解更多信息:

  1. Graphics Raycaster of Unity; How does it work?
  2. Raycast against UI in world space
  3. How to raycast against uGUI objects from an arbitrary screen/canvas position
  4. How do you perform a Graphic Raycast?
  5. GraphicRaycaster
  6. 希望它有所帮助。

答案 1 :(得分:1)

Umair M目前的建议没有处理射线来自世界空间并以一定角度行进的事实。

对我而言,即使你的画布位于世界空间,你也不能在某个角度在世界空间中进行GUI光线投射。 This page建议了一种创建非渲染摄影机的技术,使用您想要投射的光线在3D空间中移动它,然后相对于该摄像机进行GUI光线投射。我还没试过,但听起来很有希望。