PartialBillboard.cs 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. using UnityEngine;
  2. public class LimitedBillboard : MonoBehaviour
  3. {
  4. public Camera targetCamera;
  5. [Header("Y轴(左右)限制")]
  6. public float minYAngle = -45f;
  7. public float maxYAngle = 45f;
  8. [Header("X轴(上下)限制")]
  9. public float minXAngle = -20f;
  10. public float maxXAngle = 20f;
  11. private Vector3 initialForward;
  12. void Start()
  13. {
  14. if (targetCamera == null)
  15. targetCamera = Camera.main;
  16. // 记录初始朝向(用于相对旋转)
  17. initialForward = transform.forward;
  18. }
  19. void Update()
  20. {
  21. if (targetCamera == null) return;
  22. Vector3 directionToCamera = targetCamera.transform.position - transform.position;
  23. // 计算相对方向
  24. Quaternion lookRotation = Quaternion.LookRotation(directionToCamera);
  25. Vector3 targetEuler = lookRotation.eulerAngles;
  26. // 处理角度跨越360°的情况(转换为 -180 ~ 180)
  27. float yAngle = Mathf.DeltaAngle(0f, targetEuler.y - transform.eulerAngles.y);
  28. float xAngle = Mathf.DeltaAngle(0f, targetEuler.x - transform.eulerAngles.x);
  29. // 限制角度
  30. yAngle = Mathf.Clamp(yAngle, minYAngle, maxYAngle);
  31. xAngle = Mathf.Clamp(xAngle, minXAngle, maxXAngle);
  32. // 应用角度(保留当前本地角度,只改X和Y)
  33. Vector3 currentEuler = transform.eulerAngles;
  34. currentEuler.y += yAngle;
  35. currentEuler.x += xAngle;
  36. transform.eulerAngles = currentEuler;
  37. }
  38. }