如何在WorldSpace UI中使用Graphic Raycaster?

Woj*_*cel 5 unity-game-engine

我试图弄清楚Graphic.Raycaster的工作方式,但文档无济于事。我想用它从某个位置以某个角度投射光线投射并点击UI。另一件事是我不知道如何使其与UI交互(拖动,单击等)。我知道这是一个广泛的主题,但是我找不到如何使用它的任何好方法,因此,我将不胜感激。

Uma*_*r M 6

来自Unity文档:

图形射线发生器用于对Canvas进行射线广播。Raycaster会查看画布上的所有图形,并确定是否有任何图形被命中。

您可以使用EventSystem.RaycastAllraycast反对graphics(UI)元素。

这是您的情况的一个简短示例:

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();
     }
   }
}
Run Code Online (Sandbox Code Playgroud)

上面的脚本未经我本人测试。因此可能存在一些错误。

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

  1. Unity图形雷卡斯特;它是如何工作的?
  2. 针对世界空间中的UI进行Raycast
  3. 如何从任意屏幕/画布位置对uGUI对象进行光线投射
  4. 您如何执行图形射线广播?
  5. GraphicRaycaster

希望能帮助到你。