美文网首页
UI跟随相机视角旋转

UI跟随相机视角旋转

作者: Moment__格调 | 来源:发表于2017-08-07 16:47 被阅读34次

将脚本挂载到UI上:

// Licensed under the MIT License. See LICENSE in the project root for license information.

using UnityEngine;

namespace HoloToolkit.Unity
{
    //枢轴
    public enum PivotAxis
    {
        // Rotate about all axes.
        //对所有轴旋转。
        Free,
        // Rotate about an individual axis.
        //绕一个轴旋转。
        Y
    }

    /// <summary>
    /// The Billboard class implements the behaviors needed to keep a GameObject oriented towards the user.
    /// 广告牌类实现所需的行为保持GameObject面向用户。
    /// </summary>
    public class Billboard : MonoBehaviour
    {
        /// <summary>
        /// The axis about which the object will rotate.
        /// 关于对象将轴旋转。
        /// </summary>
        /// 指定对象将旋转的轴。
        [Tooltip("Specifies the axis about which the object will rotate.")]
        public PivotAxis PivotAxis = PivotAxis.Free;
        //指定了目标我们将东方。如果没有指定目标的主要将使用相机。
        [Tooltip("Specifies the target we will orient to. If no Target is specified the main camera will be used.")]
        //目标转换
        public Transform TargetTransform;

        private void OnEnable()
        {
            if (TargetTransform == null)
            {
                TargetTransform = Camera.main.transform;
            }

            Update();
        }

        /// <summary>
        /// Keeps the object facing the camera.
        /// 保持相机所面临的对象。
        /// </summary>
        private void Update()
        {
            if (TargetTransform == null)
            {
                return;
            }

            // Get a Vector that points from the target to the main camera.
            //得到一个向量点从目标到主相机。
            Vector3 directionToTarget = TargetTransform.position - transform.position;

            // Adjust for the pivot axis.
            //枢轴的调整。
            switch (PivotAxis)
            {
                case PivotAxis.Y:
                    directionToTarget.y = 0.0f;
                    break;

                case PivotAxis.Free:
                default:
                    // No changes needed.
                    break;
            }

            // If we are right next to the camera the rotation is undefined. 
            //如果我们旁边相机旋转是未定义的
            if (directionToTarget.sqrMagnitude < 0.001f)
            {
                return;
            }

            // Calculate and apply the rotation required to reorient the object
            //计算和应用所需的旋转调整对象
            transform.rotation = Quaternion.LookRotation(-directionToTarget);
        }
    }
}

相关文章

网友评论

      本文标题:UI跟随相机视角旋转

      本文链接:https://www.haomeiwen.com/subject/dsealxtx.html