Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using UnityEngine;
- #if UNITY_EDITOR
- [ExecuteInEditMode, RequireComponent(typeof(SpriteRenderer))]
- #endif
- public class Billboard : MonoBehaviour
- {
- #region Methods
- private void Start()
- {
- doNotOptimize = true;
- GetComponent<SpriteRenderer>().flipX = false;
- if (applyRandomZRotation)
- {
- randomZRotation = new float[] { 0, -90, 180, 90 }[Random.Range(0, 4)];
- }
- }
- #endregion
- #region Camera Facing Rotation
- private void OnWillRenderObject()
- {
- Camera camera = Camera.current;
- if (camera == null)
- {
- return;
- }
- if (!doNotOptimize)
- {
- updateTimer += Time.deltaTime;
- if (updateTimer < updateInterval)
- {
- return;
- }
- updateInterval = Vector3.Distance(transform.position, camera.transform.position) / UpdateFrequency;
- updateTimer = 0;
- }
- Vector3 eulers = camera.transform.eulerAngles;
- Vector3 current = transform.eulerAngles;
- float x = billboardX ? eulers.x : current.x;
- float y = billboardY ? eulers.y : current.y;
- float z = applyRandomZRotation ? randomZRotation : current.z;
- if (shaking && Time.timeScale != 0f)
- {
- x += Random.Range(-32f, 32f);
- y += Random.Range(-32f, 32f);
- z += Random.Range(-32f, 32f);
- }
- transform.rotation = Quaternion.Euler(x, y, z);
- }
- #endregion
- #region Inspector Configuration
- [Header("Billboard Settings")]
- public bool doNotOptimize;
- [SerializeField] private bool shaking, applyRandomZRotation;
- [SerializeField] private bool billboardX = true;
- [SerializeField] private bool billboardY = true;
- #endregion
- #region Runtime State and Timing
- private const float UpdateFrequency = 400f;
- private float updateTimer, updateInterval, randomZRotation;
- #endregion
- }
Advertisement
Add Comment
Please, Sign In to add comment