實現一個基於屏幕後處理的熱場空氣扭曲效果,用來烘托戰場氛圍。原理其實很是簡單,對於渲染完成的貼圖作一個擾動效果便可。app
代碼(掛在主camera上纔有效果):ide
using UnityEngine; using System.Collections; [ExecuteInEditMode] [RequireComponent(typeof(Camera))] public class PostEffectBase : MonoBehaviour { public Shader shader = null; private Material _material = null; public Material _Material { get { if (_material == null) _material = GenerateMaterial(shader); return _material; } } protected Material GenerateMaterial(Shader shader) { if (shader == null) return null; if (shader.isSupported == false) return null; Material material = new Material(shader); material.hideFlags = HideFlags.DontSave; if (material != null) return material; return null; } } using UnityEngine; using System.Collections; public class ScreenWaveEffect : PostEffectBase { [Range(-1f, 1f)] public float speedX = 0.1f; [Range(-1f, 1f)] public float speedY = 0.1f; [Range(0.0f, 1f)] public float strength = 0.1f; public Texture noiseTex; void OnRenderImage(RenderTexture src, RenderTexture dest) { if (_Material) { _Material.SetFloat("_speedX", speedX); _Material.SetFloat("_speedY", speedY); _Material.SetFloat("_strength", strength); _Material.SetTexture("_NoiseTex", noiseTex); Graphics.Blit(src, dest, _Material); } else { Graphics.Blit(src, dest); } } }
屏幕效果shader:ui
Shader "James/ScreenEffect/ScreenWaveEffect" { Properties { _MainTex("Albedo (RGB)", 2D) = "white" {} _NoiseTex("WaveTex (RGB)", 2D) = "white" {} } SubShader { Pass { ZTest Always Cull Off ZWrite Off CGPROGRAM sampler2D _MainTex, _NoiseTex; half4 _NoiseTex_ST; half _speedX, _speedY, _strength; #pragma vertex vert #pragma fragment frag #include "Lighting.cginc" struct v2f { float4 pos : SV_POSITION; half2 uv : TEXCOORD0; }; v2f vert(appdata_img v) { v2f o; o.pos = UnityObjectToClipPos(v.vertex); o.uv = v.texcoord; return o; } fixed4 frag(v2f i) : SV_Target { half2 uvNoise = i.uv; uvNoise.x += _Time.y * _speedX; uvNoise.y += _Time.y * _speedY; fixed4 noiseTex = tex2D(_NoiseTex, uvNoise); half2 uvWave = i.uv + noiseTex.xy * _strength; fixed4 renderTex = tex2D(_MainTex, uvWave); return renderTex; } ENDCG } } FallBack Off }
camera上腳本設置:spa
參數說明:code
shader:直接將上述shader拖過去便可blog
speedx/speedy:橫向和縱向擾動的速度圖片
strength:擾動的強度ip
noise tex:噪音貼圖(擾動貼圖),決定了擾動的效果get
運行效果以下:it
說明:火焰貼圖來自百度圖片