unity3d 在玩家Unity VR面前显示UI

ryevplcw  于 2022-12-04  发布在  其他
关注(0)|答案(1)|浏览(390)

在Unity3D虚拟现实项目中,我尝试在玩家面前显示一个UI,并面对它。我使用的是Unity 2021.3.5f1。
我有一个简单的用户界面:一个Canvas,其中包含一个Panel和两个TextMeshPro。画布是空GameObject的子项,其中包含管理UI的脚本。层次结构如下:

我的目标是始终在玩家面前显示UI,面向玩家本身。为此,我编写了以下脚本:

using UnityEngine;

namespace UI
{
    public class KpPanelManager : MonoBehaviour
    {
        [SerializeField] private Transform playerHead;
        [SerializeField] private float spawnDistance = 2f;
        [SerializeField] private float yOffset = 0f;
        
        [SerializeField] private GameObject panel;
        
        private Vector3 _playerHeadForward;

        private void Awake()
        {
            _playerHeadForward = playerHead.forward;
        }

        private void Update()
        {          
            // show the panel in front of the player
            var position = playerHead.position;
            panel.transform.position = position + new Vector3(_playerHeadForward.x, yOffset, _playerHeadForward.z).normalized * spawnDistance;
            
            // rotate the panel to face the player frame by frame
            panel.transform.LookAt(new Vector3(position.x, panel.transform.position.y, position.z));
            panel.transform.forward *= -1;
        }
    }
}

但是,它不能正常工作:在Unity编辑器中,我将包含UI的Canvas引用为脚本中的panel GameObject,将XROriginMainCamera引用为脚本中的playerHead Transform
有人能帮我吗?

os8fio9y

os8fio9y1#

可以使用Transform的TransformPoint()将位置从局部空间转换到世界空间
类似以下的内容将适用于您的情况

Vector3 offset = new Vector3(0,0,2); // 2 units in front of camera
panel.transform.position = playerHead.TransformPoint(offset);

相关问题