我在使用 Unity 在 VR 中拖放对象时遇到问题



我正在尝试拖放一个3d对象。我用鼠标在编辑器中让它工作,但每当我试图让它在VR中工作时,它都会跟随相机而不是LineRenderer。这是我的代码:

using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;
using UnityEngine.XR.Interaction.Toolkit;
using UnityEngine.XR.Interaction.Toolkit.UI;
public class XRDragDrop : MonoBehaviour, IPointerDownHandler, IBeginDragHandler, IEndDragHandler, IDragHandler
{
private Vector3 mOffset;
private float mZCoord;
[SerializeField]
private LineRenderer leftLineRenderer;
[SerializeField]
private LineRenderer rightLineRenderer;

public void OnDrag(PointerEventData eventData)
{
transform.position = GetReticleWorldPos() + mOffset;
}
public void OnPointerDown(PointerEventData eventData)
{
Debug.Log(eventData.currentInputModule);
mZCoord = Camera.main.WorldToScreenPoint(transform.position).z;
mOffset = gameObject.transform.position - GetReticleWorldPos();
}
private Vector3 GetReticleWorldPos()
{
// Vector3 reticlePoint = rightLineRenderer.GetPosition(1);
Vector3 reticlePoint = Input.mousePosition;
reticlePoint.z = mZCoord;
return Camera.main.ScreenToWorldPoint(reticlePoint);
}
public void OnBeginDrag(PointerEventData eventData)
{
Debug.Log("OnBeginDrag");
}
public void OnEndDrag(PointerEventData eventData)
{
Debug.Log("OnEndDrag");
}
}

我尝试过使用注释掉的代码来获取标线的位置,但它给出的结果与只获取鼠标位置完全相同。有人知道为什么对象会跟随摄影机而不是线渲染器吗?

原来我是个十足的白痴,因为我可以使用rightLineRenderer.GetPosition(1(获得指针位置,我甚至不需要使用ScreenToWorldPoint转换它,因为它已经是一个世界位置了。然而,我设法以一种更简单的方式完成了我想要的事情,只需要使用PointerEventData就可以减少代码。以下是我所做的:

using UnityEngine;
using UnityEngine.EventSystems;
public class XRDragDrop : MonoBehaviour, IPointerDownHandler, IDragHandler
{
private Vector3 mOffset;

public void OnDrag(PointerEventData eventData)
{
transform.position = eventData.pointerCurrentRaycast.worldPosition + mOffset;
}
public void OnPointerDown(PointerEventData eventData)
{
mOffset = gameObject.transform.position - eventData.pointerCurrentRaycast.worldPosition;
}
}

最新更新