Guest User

Billboard Script

a guest
Mar 18th, 2026
226
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.99 KB | None | 0 0
  1. using UnityEngine;
  2.  
  3. #if UNITY_EDITOR
  4. [ExecuteInEditMode, RequireComponent(typeof(SpriteRenderer))]
  5. #endif
  6. public class Billboard : MonoBehaviour
  7. {
  8. #region Methods
  9. private void Start()
  10. {
  11. doNotOptimize = true;
  12. GetComponent<SpriteRenderer>().flipX = false;
  13.  
  14. if (applyRandomZRotation)
  15. {
  16. randomZRotation = new float[] { 0, -90, 180, 90 }[Random.Range(0, 4)];
  17. }
  18. }
  19. #endregion
  20.  
  21. #region Camera Facing Rotation
  22. private void OnWillRenderObject()
  23. {
  24. Camera camera = Camera.current;
  25. if (camera == null)
  26. {
  27. return;
  28. }
  29.  
  30. if (!doNotOptimize)
  31. {
  32. updateTimer += Time.deltaTime;
  33. if (updateTimer < updateInterval)
  34. {
  35. return;
  36. }
  37.  
  38. updateInterval = Vector3.Distance(transform.position, camera.transform.position) / UpdateFrequency;
  39. updateTimer = 0;
  40. }
  41.  
  42. Vector3 eulers = camera.transform.eulerAngles;
  43. Vector3 current = transform.eulerAngles;
  44.  
  45. float x = billboardX ? eulers.x : current.x;
  46. float y = billboardY ? eulers.y : current.y;
  47. float z = applyRandomZRotation ? randomZRotation : current.z;
  48.  
  49. if (shaking && Time.timeScale != 0f)
  50. {
  51. x += Random.Range(-32f, 32f);
  52. y += Random.Range(-32f, 32f);
  53. z += Random.Range(-32f, 32f);
  54. }
  55.  
  56. transform.rotation = Quaternion.Euler(x, y, z);
  57. }
  58. #endregion
  59.  
  60. #region Inspector Configuration
  61. [Header("Billboard Settings")]
  62. public bool doNotOptimize;
  63. [SerializeField] private bool shaking, applyRandomZRotation;
  64. [SerializeField] private bool billboardX = true;
  65. [SerializeField] private bool billboardY = true;
  66. #endregion
  67.  
  68. #region Runtime State and Timing
  69. private const float UpdateFrequency = 400f;
  70. private float updateTimer, updateInterval, randomZRotation;
  71. #endregion
  72. }
Advertisement
Add Comment
Please, Sign In to add comment