LoadingFade.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. //======= Copyright (c) Stereolabs Corporation, All rights reserved. ===============
  2. using UnityEngine;
  3. /// <summary>
  4. /// Fades the screen from black to the ZED image when the ZED camera is first opened.
  5. /// Added to the relevant cameras by ZEDRenderingPlane when ZED is initialized.
  6. /// </summary>
  7. public class LoadingFade : MonoBehaviour
  8. {
  9. /// <summary>
  10. /// Material used to perform the fade.
  11. /// </summary>
  12. private Material fader;
  13. /// <summary>
  14. /// Current alpha value of the black overlay used to darken the image.
  15. /// </summary>
  16. private float alpha;
  17. /// <summary>
  18. /// Start flag. Set to true when the ZED is opened.
  19. /// </summary>
  20. private bool start = false;
  21. /// <summary>
  22. /// Sets the alpha to above 100% (to add a delay to the effect) and loads the fade material.
  23. /// </summary>
  24. void Start ()
  25. {
  26. alpha = 1.5f;
  27. fader = new Material(Resources.Load("Materials/GUI/Mat_ZED_Fade") as Material);
  28. }
  29. private void OnEnable()
  30. {
  31. start = true;
  32. }
  33. private void OnDisable()
  34. {
  35. start = false;
  36. }
  37. /// <summary>
  38. /// Applies the darkening effect to the camera's image.
  39. /// Called by Unity every time the camera it's attached to renders an image.
  40. /// </summary>
  41. /// <param name="source"></param>
  42. /// <param name="destination"></param>
  43. private void OnRenderImage(RenderTexture source, RenderTexture destination)
  44. {
  45. if (start)
  46. {
  47. //Lower the alpha. We use hard-coded values instead of using Time.deltaTime
  48. //to simplify things, but the function is quite customizable.
  49. alpha -= EaseIn(0.4f, 0, 0.5f, 1.5f);
  50. }
  51. alpha = alpha < 0 ? 0 : alpha; //Clamp the alpha at 0.
  52. fader.SetFloat("_Alpha", alpha); //Apply the new alpha to the fade material.
  53. Graphics.Blit(source, destination, fader); //Render the image effect from the camera's output.
  54. if (alpha == 0) Destroy(this); //Remove the component when the fade is over.
  55. }
  56. /// <summary>
  57. /// An ease-in function for reducing the alpha value each frame.
  58. /// </summary>
  59. /// <param name="t">Current time.</param>
  60. /// <param name="b">Start value.</param>
  61. /// <param name="c">Value change multiplier.</param>
  62. /// <param name="d">Duration.</param>
  63. /// <returns>New alpha value.</returns>
  64. static float EaseIn(float t, float b, float c, float d)
  65. {
  66. return -c * (Mathf.Sqrt(1 - (t /= d) * t) - 1) + b;
  67. }
  68. }