LookAtCamera.cs 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. #if ZED_HDRP || ZED_URP
  5. using UnityEngine.Rendering;
  6. #endif
  7. /// <summary>
  8. /// Makes the GameObject turn to face the target object each frame.
  9. /// Used for an outline effect on the ZED planetarium sample's sun, as it's drawn by a quad.
  10. /// </summary>
  11. public class LookAtCamera : MonoBehaviour
  12. {
  13. #if !ZED_HDRP && !ZED_URP //OnWillRenderObject doesn't work in SRP, so use a callback from RenderPipeline to trigger the facing instead.
  14. void OnWillRenderObject()
  15. {
  16. FaceCamera(Camera.current);
  17. }
  18. #else
  19. /// <summary>
  20. /// The ZEDManager that the object will face each frame. Faces the left camera.
  21. /// </summary>
  22. [Tooltip("The ZEDManager that the object will face each frame. Faces the left camera.")]
  23. public ZEDManager zedManager;
  24. private Camera zedLeftCam;
  25. private void Start()
  26. {
  27. if(!zedManager)
  28. {
  29. zedManager = FindObjectOfType<ZEDManager>();
  30. }
  31. if (zedManager) zedLeftCam = zedManager.GetLeftCamera();
  32. }
  33. private void LateUpdate()
  34. {
  35. if (zedLeftCam) FaceCamera(zedLeftCam);
  36. }
  37. #endif
  38. void FaceCamera(Camera cam)
  39. {
  40. Camera targetcam = cam; //Shorthand.
  41. //Make sure the target and this object don't have the same position. This can happen before the cameras are initialized.
  42. //Calling Quaternion.LookRotation in this case spams the console with errors.
  43. if (transform.position - targetcam.transform.position == Vector3.zero)
  44. {
  45. return;
  46. }
  47. transform.rotation = Quaternion.LookRotation(transform.position - targetcam.transform.position);
  48. }
  49. }