Lev*_*vin 2 c# unity-game-engine raycasting
出于某种原因,当 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
您不能Physics.Raycast
为 UI 元素使用 a ,也不能使用2D 碰撞器。
一般来说,您想要点击的是特定的Graphic
组件,例如启用的Image
或Text
组件RaycastTarget
。
如果你想打 aBoxCollider2D
你就必须使用Physics2D.Raycast
代替。然而,这并不用于在Z
方向上进行光线投射,而仅适用于通过 XY 方向从侧面撞击对撞机。
为了实际击中 UI,你必须使用不同类型的 Raycast,而不是通过物理,而是使用EventSystem.RaycastAll
类似的,例如
var pointerEventData = new pointerEventData{ position = touchPos};
var raycastResults = new List<RaycastResult>();
EventSystem.current.RaycastAll(pointerEventData, raycastResults);
if(raycastResults.Count > 0)
{
foreach(var result in RaycastResults)
{
...
}
}
Run Code Online (Sandbox Code Playgroud)
进一步注意,您检查了 tagChallangeUI
但您的 UI 对象具有 layer UI
。