效果圖:
shader 代碼
Shader "My/WaveDiffusion" { Properties { //shader放一張圖片,圖片需要與要顯示模型上材質球上圖片一致,不放沒有效果, _MainTex("Texture", 2D) = "white" {} } SubShader { Cull Off ZWrite Off ZTest Always Pass { CGPROGRAM #pragma vertex vert #pragma fragment frag #include "UnityCG.cginc" struct appdata { float4 vertex : POSITION; float2 uv : TEXCOORD0; }; struct v2f { float2 uv : TEXCOORD0; float4 vertex : SV_POSITION; }; v2f vert(appdata v) { v2f o; o.vertex = UnityObjectToClipPos(v.vertex); o.uv = v.uv; return o; } sampler2D _MainTex; sampler2D _CameraDepthTexture; float4x4 _VPMatrix4x4_inverse; float4 _WaveColor; float4 _WaveCenter; float _WaveSpeed; float _WaveInterval; float _WavePower; float _WaveColorPower; fixed4 frag(v2f i) : SV_Target { fixed4 col = tex2D(_MainTex, i.uv); fixed depth = tex2D(_CameraDepthTexture, i.uv).r; fixed4 ndc = fixed4(i.uv.x * 2 - 1, i.uv.y * 2 - 1, -depth * 2 + 1, 1); fixed4 worldPos = mul(_VPMatrix4x4_inverse, ndc); worldPos /= worldPos.w; float mask = 1 - Linear01Depth(depth); float dis = length(worldPos.xyz - _WaveCenter.xyz); dis -= _Time.y * _WaveSpeed; dis /= _WaveInterval; dis = dis - floor(dis); dis = (pow(dis, _WavePower) + pow(1 - dis, _WavePower * 4)) * 0.5; dis *= _WaveColorPower; return dis * mask * _WaveColor + col; } ENDCG } } }
c#代碼
using System.Collections; using System.Collections.Generic; using UnityEngine; /// <summary> /// 本腳本掛到攝像機上 /// </summary> public class WaveDiffusion_Postprocessing : MonoBehaviour { public Shader waveDiffusionShader; public Vector4 waveCenter = Vector4.zero; //擴散中心 public Color waveColor = Color.red; //波紋顏色 public float waveSpeed = 1; //擴散速度 public float waveInterval = 5; //擴散間隔 public float wavePower = 10; //波紋強度 public float waveColorPower = 10; //波紋顏色強度 private Material waveDiffusionMat; //渲染材質 private Matrix4x4 vpMatrix4x4_inverse; //VP逆矩陣 private void Start() { //設置相機獲取深度 Camera.main.depthTextureMode = DepthTextureMode.Depth; waveDiffusionMat = new Material(waveDiffusionShader); //計算VP逆矩陣 Matrix4x4 vpMatrix4x4_inverse = Camera.main.projectionMatrix * Camera.main.worldToCameraMatrix; vpMatrix4x4_inverse = vpMatrix4x4_inverse.inverse; //設置矩陣 waveDiffusionMat.SetMatrix("_VPMatrix4x4_inverse", vpMatrix4x4_inverse); } private void OnRenderImage(RenderTexture src, RenderTexture dst) { //設置渲染材質參數 waveDiffusionMat.SetVector("_WaveCenter", waveCenter); waveDiffusionMat.SetFloat("_WaveSpeed", waveSpeed); waveDiffusionMat.SetFloat("_WaveInterval", waveInterval); waveDiffusionMat.SetFloat("_WavePower", wavePower); waveDiffusionMat.SetFloat("_WaveColorPower", waveColorPower); waveDiffusionMat.SetColor("_WaveColor", waveColor); //渲染 Graphics.Blit(src, dst, waveDiffusionMat); } }
shader放一張圖片,圖片需要與要顯示模型上材質球上圖片一致,不放沒有效果
我用的是plane 腳本設置參數如下

根據自己需要調整
喜歡的話點個贊吧😘😘
