Unity贴花的实现
大致原理是在相机空间下,将贴花所在的物体顶点投射到远裁平面,再根据深度图来获取深度,然后两者相乘,重新映射到要贴的物体表面上,当然队列要比要贴的物体大。
以下是代码解析
v2f vert (appdata_base v)
{
v2f o;
o.pos = UnityObjectToClipPos (v.vertex);
o.screenUV = ComputeScreenPos (o.pos);
o.ray = UnityObjectToViewPos(v.vertex).xyz * float3(1, 1, -1);
return o;
}
sampler2D _MainTex;
sampler2D _CameraDepthTexture;
float4 frag(v2f i) : SV_Target
{
i.ray = i.ray * (_ProjectionParams.z / i.ray.z);
float2 uv = i.screenUV.xy / i.screenUV.w;
float depth = SAMPLE_DEPTH_TEXTURE(_CameraDepthTexture, uv);
depth = Linear01Depth (depth);
float4 vpos = float4(i.ray * depth,1);
float3 wpos = mul (unity_CameraToWorld, vpos).xyz;
float3 opos = mul (unity_WorldToObject, float4(wpos,1)).xyz;
clip (float3(0.5,0.5,0.5) - abs(opos.xyz));
float2 texUV = opos.xz + 0.5;
float4 col = tex2D (_MainTex, texUV);
return col;
}
代码参考地址:https://blog.csdn.net/weixin_45023328/article/details/114968697
|