I have been testing writing shaders for 3D UI purposes. I made an unlit, cutoff shader that will render only what is inside a box with a fading effect before clipping.
I have issues with the transparency effect, which works in the editor but not in play mode.
The transparency works well when seen from the editor :
But it doesn’t look the same when viewed from the camera :
These pictures were taken with a _Transparency value of 0.25, from the following shader :
Shader "Custom/HoloProj_RenderInVisibleVolumes"
{
Properties
{
_Color("Color", Color) = (1, 1, 1, 1)
_MainTex ("Texture", 2D) = "white" {}
_Transparency("Transparency", Range(0.0, 1)) = 0.5
}
SubShader
{
Tags { "RenderType" = "Transparent" }
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
Cull Off
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#include "UnityCG.cginc"
struct appdata
{
float4 vertex : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f
{
float2 uv : TEXCOORD0;
float3 wpos : TEXCOORD1;
float4 vertex : SV_POSITION;
fixed4 color : COLOR0;
};
float4x4 _WorldToBox;
sampler2D _MainTex;
float4 _MainTex_ST;
float4 _Color;
float _Transparency;
float max3 (float3 v) {
return max (max (v.x, v.y), v.z);
}
v2f vert (appdata v)
{
v2f o;
o.vertex = UnityObjectToClipPos(v.vertex);
o.uv = TRANSFORM_TEX(v.uv, _MainTex);
o.wpos = mul(unity_ObjectToWorld, v.vertex);
o.color = _Color;
return o;
}
fixed4 frag (v2f i) : SV_Target
{
// Computes visibility volume position relative to vertex.
float3 boxPosition = mul(_WorldToBox, float4(i.wpos, 1));
// Prevents vertex outside of the visibility volume to be drawn.
clip(boxPosition + 0.5);
clip(0.5 - boxPosition);
float closest_to_threshold = max3(abs(boxPosition));
// Compute fade out transparency value.
// Smooth function : 256 = (1/0.5^8) ; pow(x, 8) is equivalent to 3 multiplications.
// Function smoothly reduces transparency from the initial _Transparency value down to 0 as vertex gets closer to the boundaries of the visiblity area.
float transparency = (-256 * pow(closest_to_threshold, 8) + 1) * _Transparency;
if (transparency < 0)
transparency = 0; // Hopefully, we may expect optimization static branching.
fixed4 col = tex2D(_MainTex, i.uv);
col.a = _Transparency;
return col * i.color;
}
ENDCG
}
}
}
You can ignore all cutoff/fading calculations as only _Transparency is applied to the color’s alpha component, which is what I use to get the transparency effect (wrongfully I guess).
In play mode, this forces me to go with much lower values, here 0.015, to get the same result I had in the editor with 0.25. The surface flickers slightly as well.
How do I properly make this transparence effect work?