123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051 |
- using UnityEngine;
- public class LimitedBillboard : MonoBehaviour
- {
- public Camera targetCamera;
- [Header("Y轴(左右)限制")]
- public float minYAngle = -45f;
- public float maxYAngle = 45f;
- [Header("X轴(上下)限制")]
- public float minXAngle = -20f;
- public float maxXAngle = 20f;
- private Vector3 initialForward;
- void Start()
- {
- if (targetCamera == null)
- targetCamera = Camera.main;
- // 记录初始朝向(用于相对旋转)
- initialForward = transform.forward;
- }
- void Update()
- {
- if (targetCamera == null) return;
- Vector3 directionToCamera = targetCamera.transform.position - transform.position;
- // 计算相对方向
- Quaternion lookRotation = Quaternion.LookRotation(directionToCamera);
- Vector3 targetEuler = lookRotation.eulerAngles;
- // 处理角度跨越360°的情况(转换为 -180 ~ 180)
- float yAngle = Mathf.DeltaAngle(0f, targetEuler.y - transform.eulerAngles.y);
- float xAngle = Mathf.DeltaAngle(0f, targetEuler.x - transform.eulerAngles.x);
- // 限制角度
- yAngle = Mathf.Clamp(yAngle, minYAngle, maxYAngle);
- xAngle = Mathf.Clamp(xAngle, minXAngle, maxXAngle);
- // 应用角度(保留当前本地角度,只改X和Y)
- Vector3 currentEuler = transform.eulerAngles;
- currentEuler.y += yAngle;
- currentEuler.x += xAngle;
- transform.eulerAngles = currentEuler;
- }
- }
|