CircleEffectHandler.cs 2.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using UnityEngine;
  4. [ExecuteInEditMode]
  5. public class CircleEffectHandler : MonoBehaviour
  6. {
  7. public Material circleEffectMaterial; //create material from shader and attatch here
  8. public float speedThreshold;
  9. GameObject cameraObject;
  10. float lagTime = 1f;
  11. // Start is called before the first frame update
  12. void Start()
  13. {
  14. angularVelocity = new Vector3(0,0,0);
  15. StartCoroutine(TrackAngularVelocity());
  16. cameraObject = GetComponent<Camera>().gameObject;
  17. circleEffectMaterial.SetFloat("_blackRatio", 1);
  18. }
  19. // Update is called once per frame
  20. void Update()
  21. {
  22. }
  23. IEnumerator CircleFadeRoutine(){
  24. yield return null;
  25. float t = 0;
  26. //fade in
  27. while(t < lagTime){
  28. t+=Time.deltaTime;
  29. circleEffectMaterial.SetFloat("_blackRatio", 1f - t/lagTime);
  30. yield return null;
  31. }
  32. circleEffectMaterial.SetFloat("_blackRatio", 0);
  33. while(angularVelocity.magnitude > speedThreshold){
  34. circleEffectMaterial.SetFloat("_blackRatio", 0);
  35. yield return null;
  36. }
  37. t = 0;
  38. //fade in
  39. while(t < lagTime){
  40. t+=Time.deltaTime;
  41. circleEffectMaterial.SetFloat("_blackRatio", t/lagTime);
  42. yield return null;
  43. }
  44. circleEffectMaterial.SetFloat("_blackRatio",1);
  45. lagging = false;
  46. }
  47. Vector3 angularVelocity;
  48. bool lagging = false;
  49. IEnumerator TrackAngularVelocity(){
  50. Vector3 lastRotation = new Vector3(0,0,0);
  51. while(true){
  52. yield return null;
  53. Vector3 delta = cameraObject.transform.localEulerAngles - lastRotation;
  54. lastRotation = cameraObject.transform.localEulerAngles;
  55. angularVelocity = delta / Time.deltaTime;
  56. }
  57. }
  58. void OnRenderImage(RenderTexture src, RenderTexture dst){
  59. if(angularVelocity.magnitude > speedThreshold && !lagging){
  60. lagging = true;
  61. StartCoroutine(CircleFadeRoutine());
  62. }
  63. RenderTexture renderTexture = RenderTexture.GetTemporary(src.width, src.height);
  64. Graphics.Blit(src, renderTexture); //copies source texture to destination texture
  65. //apply the render texture as many iterations as specified
  66. RenderTexture tempTexture = RenderTexture.GetTemporary(src.width, src.height); //creates a quick temporary texture for calculations
  67. Graphics.Blit(renderTexture, tempTexture, circleEffectMaterial);
  68. RenderTexture.ReleaseTemporary(renderTexture); //releases the temporary texture we got from GetTemporary
  69. renderTexture = tempTexture;
  70. Graphics.Blit(renderTexture, dst);
  71. RenderTexture.ReleaseTemporary(renderTexture);
  72. }
  73. }