unity软粒子softparticle仿真实现
作者:互联网
unity粒子系统自带了软粒子shader,目的是当粒子的billboard与场景中的多边形相交时,产生一个过渡,避免出现生硬的边界
本文还原一下这个shader处理方式
运行效果图如下:
基本原理就是,在shader的片元处理阶段,判断当前像素点的视深,与_CameraDepthTexture里的深度差值,
如果深度小于某个阀值,对alpha进行加一个衰减,产生过渡效果
对应的shader代码如下:
Shader "lsc/UnlitShader_softparticle"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
}
SubShader
{
Tags { "RenderType"="Opaque" }
LOD 100
Blend SrcAlpha OneMinusSrcAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
// make fog work
//#pragma multi_compile_fog
//#pragma multi_compile_particles
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
//UNITY_FOG_COORDS(1)
float4 vertex : SV_POSITION;
float4 screen_space : TEXCOORD1;
};
sampler2D _MainTex;
float4 _MainTex_ST;
sampler2D _CameraDepthTexture;
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
//UNITY_TRANSFER_FOG(o,o.vertex);
// lsc 计算屏幕空间 xy为屏幕坐标, z为视深
o.screen_space = ComputeScreenPos(o.vertex);
COMPUTE_EYEDEPTH(o.screen_space.z);
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// sample the texture
fixed4 col = tex2D(_MainTex, i.uv);
// lsc 去掉齐次因子(只能在片元着色器里去掉,保证线性插值)
float2 screen_pos = i.screen_space.xy / i.screen_space.w;
// lsc 取出深度纹理
float depth01 = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, screen_pos.xy);
// lsc 取出线性视深度,即摄影机空间的z坐标
float linearDepthZ = LinearEyeDepth(depth01);
// lsc 根据深度差值,计算附加的透明度alpha_scale
float dep_diff = linearDepthZ - i.screen_space.z;
float alpha_scale = (dep_diff - 1.0f) / 1.0f;
float final_alpha = alpha_scale * col.a;
col.a = final_alpha;
// apply fog
//UNITY_APPLY_FOG(i.fogCoord, col);
return col;
}
ENDCG
}
}
}
标签:仿真,lsc,space,screen,vertex,unity,alpha,softparticle,MainTex 来源: https://blog.csdn.net/lsccsl/article/details/117926419