Unity 相机遮挡透明方案

Shader实现,不依赖碰撞体


基本思路

效果一般…

fixed4 frag(v2f i) : SV_Target
{
    // sample the texture
    fixed4 col = tex2D(_MainTex, i.uv);
 
    float3 cameraLocation = _globalCameraWorldLocation.xyz;
    float3 targetLocation = _globalCameraTargetWorldLocation.xyz;
 
    float3 cameraToTarget = targetLocation - cameraLocation;
    float3 cameraToVertex = i.worldPos - cameraLocation;
    float cosValue = mul(normalize(cameraToTarget), normalize(cameraToVertex));
 
    if (length(cameraToTarget) > length(cameraToVertex) && cosValue > 0.95)
    {
        col.a = lerp(0.8, 0.0, (cosValue - 0.95) / 0.05);
    }
 
    // apply fog
    UNITY_APPLY_FOG(i.fogCoord, col);
    return col;
}