简体   繁体   中英

Show UI in front of player Unity VR

I am trying to show a UI always in front of the player, and facing it, in a Unity3D VR project. I am using Unity 2021.3.5f1.

I have a simple UI: a Canvas , with a Panel and two TextMeshPro inside it. The Canvas is child of an empty GameObject , with a script in it that manages the UI. The hierarchy is as follows:

用户界面层次结构

My aim is to always show the UI in front of the player, facing the player itself. For this reason I wrote this script:

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;
        }
    }
}

However, it does not work properly: it is correctly in front of the player, but it does not follow the player's camera itself when it moves. In the Unity editor I am referencing the Canvas that contains my UI as the panel GameObject in script, and the MainCamera of the XROrigin as the playerHead Transform in the script.

Can anyone help me?

You could use Transform's TransformPoint() to covert position from local to world space

Something like following would work for your case

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM