一、使用场景
在一些情况下我们需要UI朝向摄像机,比如血条。
二、遇到的问题
首先想到的方法是:
transform.forward = cam.transform.forward;
但是当相机的X轴旋转超过90度时,UI的X轴和Y轴会发生反转。
三、解决方案
所以解决方案是使Camera的up方向为向上方向,代码为:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;public class ArmAngleUI : MonoBehaviour
{private Camera cam;private void OnEnable(){cam = Camera.main;}private void Update(){Vector3 adjustedForward = cam.transform.forward;Vector3 adjustedUp = cam.transform.up;// 创建一个旋转,使UI正面对准摄像机的forward方向,并保持摄像机的up方向作为"向上"transform.rotation = Quaternion.LookRotation(adjustedForward, adjustedUp);}
}