利用NDC坐标实现画面渐隐效果

作者:追风剑情 发布于:2017-9-15 18:47 分类:Shader

NDC坐标:把裁剪空间中的坐标归一化后得到的坐标。取值范围[-1,1]

示例:让屏幕画面渐隐

工程如图

1111111.png

FadeOut.shader代码


  1. Shader "Custom/FadeOut"
  2. {
  3. Properties
  4. {
  5. //材质面板中隐藏_MainTex
  6. [PerRendererData] _MainTex ("Texture", 2D) = "white" {}
  7. [MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
  8. }
  9. SubShader
  10. {
  11. Tags
  12. {
  13. "Queue"="Transparent"
  14. "IgnoreProjector"="True"
  15. "RenderType"="Transparent"
  16. //默认预览样式Plane
  17. "PreviewType"="Plane"
  18. //支持Sprite
  19. "CanUseSpriteAtlas"="True"
  20. }
  21. LOD 100
  22. Cull Off
  23. Lighting Off
  24. ZWrite Off
  25. Fog { Mode Off }
  26. Blend SrcAlpha OneMinusSrcAlpha
  27.  
  28. Pass
  29. {
  30. CGPROGRAM
  31. #pragma vertex vert
  32. #pragma fragment frag
  33. // make fog work
  34. #pragma multi_compile_fog
  35. #pragma multi_compile PIXELSNAP_ON
  36. #include "UnityCG.cginc"
  37.  
  38. struct appdata
  39. {
  40. float4 vertex : POSITION;
  41. float2 uv : TEXCOORD0;
  42. };
  43.  
  44. struct v2f
  45. {
  46. float2 uv : TEXCOORD0;
  47. UNITY_FOG_COORDS(1)
  48. float4 vertex : SV_POSITION;
  49. //NDC坐标
  50. float2 ndc_uv : TEXCOORD1;
  51. };
  52.  
  53. sampler2D _MainTex;
  54. float4 _MainTex_ST;
  55. v2f vert (appdata v)
  56. {
  57. v2f o;
  58. o.vertex = UnityObjectToClipPos(v.vertex);
  59. o.uv = TRANSFORM_TEX(v.uv, _MainTex);
  60. UNITY_TRANSFER_FOG(o,o.vertex);
  61. //NDC坐标=裁剪空间坐标/w
  62. o.ndc_uv = v.vertex.xy / v.vertex.w;
  63. #ifdef PIXELSNAP_ON
  64. o.vertex = UnityPixelSnap (o.vertex);
  65. #endif
  66. return o;
  67. }
  68. fixed4 frag (v2f i) : SV_Target
  69. {
  70. //ndc的z坐标取值范围[-1,1]——OpenGL
  71. //ndc的z坐标取值范围[0, 1]——DirectX
  72. //ndc的x,y坐标取值范围[0,1]
  73. //alpha取值范围[0,1]
  74. float a = i.ndc_uv.y;
  75. // sample the texture
  76. fixed4 col = tex2D(_MainTex, i.uv);
  77. col.a = a;
  78. // apply fog
  79. UNITY_APPLY_FOG(i.fogCoord, col);
  80. return col;
  81. }
  82. ENDCG
  83. }
  84. }
  85. }


使用FadeOut.shader前的效果

2222.png

使用FadeOut.shader后的效果

333333.png


参考 http://blog.csdn.net/manwithrose/article/details/23704625

标签: Shader

Powered by emlog  蜀ICP备18021003号-1   sitemap

川公网安备 51019002001593号