MotionBlur.cs 2.0 KB

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