MotionBlur.cs 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. using System;
  2. using UnityEngine;
  3. // This class implements simple ghosting type Motion Blur.
  4. // If Extra Blur is selected, the scene will allways be a little blurred,
  5. // as it is scaled to a smaller resolution.
  6. // The effect works by accumulating the previous frames in an accumulation
  7. // texture.
  8. namespace UnityStandardAssets.ImageEffects
  9. {
  10. [ExecuteInEditMode]
  11. [AddComponentMenu("Image Effects/Blur/Motion Blur (Color Accumulation)")]
  12. [RequireComponent(typeof(Camera))]
  13. public class MotionBlur : ImageEffectBase
  14. {
  15. [Range(0.0f, 0.92f)]
  16. public float blurAmount = 0.8f;
  17. public bool extraBlur = false;
  18. private RenderTexture accumTexture;
  19. override protected void Start()
  20. {
  21. base.Start();
  22. }
  23. override protected void OnDisable()
  24. {
  25. base.OnDisable();
  26. DestroyImmediate(accumTexture);
  27. }
  28. // Called by camera to apply image effect
  29. void OnRenderImage (RenderTexture source, RenderTexture destination)
  30. {
  31. // Create the accumulation texture
  32. if (accumTexture == null || accumTexture.width != source.width || accumTexture.height != source.height)
  33. {
  34. DestroyImmediate(accumTexture);
  35. accumTexture = new RenderTexture(source.width, source.height, 0);
  36. accumTexture.hideFlags = HideFlags.HideAndDontSave;
  37. Graphics.Blit( source, accumTexture );
  38. }
  39. // If Extra Blur is selected, downscale the texture to 4x4 smaller resolution.
  40. if (extraBlur)
  41. {
  42. RenderTexture blurbuffer = RenderTexture.GetTemporary(source.width/4, source.height/4, 0);
  43. Graphics.Blit(accumTexture, blurbuffer);
  44. Graphics.Blit(blurbuffer,accumTexture);
  45. RenderTexture.ReleaseTemporary(blurbuffer);
  46. }
  47. // Clamp the motion blur variable, so it can never leave permanent trails in the image
  48. blurAmount = Mathf.Clamp( blurAmount, 0.0f, 0.92f );
  49. // Setup the texture and floating point values in the shader
  50. material.SetTexture("_MainTex", accumTexture);
  51. material.SetFloat("_AccumOrig", 1.0F-blurAmount);
  52. // We are accumulating motion over frames without clear/discard
  53. // by design, so silence any performance warnings from Unity
  54. // Render the image using the motion blur shader
  55. Graphics.Blit (source, accumTexture, material);
  56. Graphics.Blit (accumTexture, destination);
  57. }
  58. }
  59. }