我如何使用画布元素(覆盖屏幕空间)使raycast命中

问题描述 投票:-1回答:1

由于某些原因,当3D对象正常工作时,我的2D叠加层对光线投射没有反应。我已经在互联网上搜索了很长时间,但仍然找不到解决方案。 (我对C#和Unity还是有点陌生​​,所以我的知识有限)

如果有人可以阐明我遇到的这个问题,将不胜感激!

这里的问题是,当我单击2D叠加层时,我希望光标显示控制台消息。 3D对象工作并在控制台中显示相关消息,但由于某些原因,2D图形无法检测到射线投射。

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.XR.ARFoundation;

public class rayCast_Test : MonoBehaviour
{
    [SerializeField]
    public GameObject TutorialUI;

    public Canvas gameChara2D;
    [SerializeField]
    private float rayCastDistance = 25f;
    [SerializeField]
    float DistanceFromCamera = 1f;

    private ARRaycastManager aRRaycastManager;
    private Vector3 touchPos;
    private Vector3 touchOrigin;



    private bool onTouchHold = false;

    private RaycastHit hitObject;



    private void Awake()
    {
        aRRaycastManager = FindObjectOfType<ARRaycastManager>();
    }

    // Update is called once per frame
    void Update()
    {


        if (Input.GetMouseButton(0))
        {
            touchPos = Input.mousePosition;

            if (!onTouchHold)
            {
                Ray ray = Camera.main.ScreenPointToRay(touchPos);


                if (Physics.Raycast(ray, out hitObject, rayCastDistance))
                {
                    if(hitObject.transform.CompareTag("Moveable"))
                    {
                        onTouchHold = true;
                        touchOrigin = Input.mousePosition;
                        Debug.Log("Hello. This is a 3D object");
                    }
                }

                if(Physics.Raycast(ray, out hitObject, rayCastDistance))
                {
                    if (hitObject.transform.CompareTag("ChallengeUI"))
                    {
                        Debug.Log("Hello. This is a 2D object");
                    }

                }
            }

        }

        if(Input.GetMouseButtonUp(0))
        {
            onTouchHold = false;
        }


    }
}

Scene TreeCanvas Properties

c# unity3d raycasting
1个回答
0
投票

您不能将Physics.Raycast用于UI元素或2D对撞机。

通常,您要点击的是特定的Graphic组件,例如启用了ImageTextRaycastTarget组件。


如果您想击打BoxCollider2D,则必须改用Physics2D.Raycast。但是,这不用于在Physics2D.Raycast方向上进行光线投射,而仅用于通过XY方向从侧面撞击对撞机。


要实际点击用户界面,您必须使用其他类型的Raycast,例如将Z组件用于GraphicRaycaster

API摘录

GraphicRaycaster.Raycast

请注意,您已经检查了标签GraphicRaycaster.Raycast,但是您的UI对象具有图层//Create a list of Raycast Results List<RaycastResult> results = new List<RaycastResult>(); //Raycast using the Graphics Raycaster and mouse click position m_Raycaster.Raycast(m_PointerEventData, results); //For every result returned, output the name of the GameObject on the Canvas hit by the Ray foreach (RaycastResult result in results) { Debug.Log("Hit " + result.gameObject.name); }

© www.soinside.com 2019 - 2024. All rights reserved.