由于某些原因,当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;
}
}
}
您不能将Physics.Raycast
用于UI元素或2D对撞机。
通常,您要点击的是特定的Graphic
组件,例如启用了Image
的Text
或RaycastTarget
组件。
如果您想击打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);
}
。