I’m currently making a 2d Platformer and I want the objects in the background to be blurred. I found a very nice shader online, but it’s probably used to blur textures of 3d objects and not sprites. I don’t know a lot about shaders, so I didn’t understand everything, but I managed to cut out the black part and the weird lines that appear sometimes.
I’m just using the alpha value of the normal texture, and not the one of the “new” texture, since that is only a color variable. The edges aren’t smooth because of that.
Does someone know how to convert this new texture or how to change the code so that it fades with the alpha?
Here is the shader code:
Shader "Blurs/GaussianBlurSinglepass"
{
Properties
{
_MainTex ("Texture", 2D) = "white" {}
_KernelSize("Kernel Size (N)", Range(0, 150)) = 21
_Spread("St. dev. (sigma)", Float) = 5.0
_Transparency("Transparency", Range(0.0, 0.5)) = 0.25
}
SubShader
{
Tags
{
"Queue" = "Transparent" "RenderType"="Transparent"
}
Pass
{
Name "BlurPass"
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert_img
#pragma fragment frag_horizontal
#include "UnityCG.cginc"
// Define the constants used in Gaussian calculation.
static const float TWO_PI = 6.28319;
static const float E = 2.71828;
sampler2D _MainTex;
float4 _MainTex_ST;
float2 _MainTex_TexelSize;
int _KernelSize;
float _Spread;
float _Transparency;
/* Implement the Gaussian function in two dimensions.
*/
float gaussian(int x, int y)
{
float sigmaSqu = _Spread * _Spread;
return (1 / sqrt(TWO_PI * sigmaSqu)) * pow(E, -((x * x) + (y * y)) / (2 * sigmaSqu));
}
float4 frag_horizontal(v2f_img i) : SV_Target
{
float3 col = float3(0.0, 0.0, 0.0);
float kernelSum = 0.0;
int upper = ((_KernelSize - 1) / 2);
int lower = -upper;
for (int x = lower; x <= upper; ++x)
{
for (int y = lower; y <= upper; ++y)
{
float gauss = gaussian(x, y);
kernelSum += gauss;
fixed2 offset = fixed2(_MainTex_TexelSize.x * x, _MainTex_TexelSize.y * y);
col += gauss * tex2D(_MainTex, i.uv + offset);
}
}
col /= kernelSum;
float transparency = tex2D (_MainTex, i.uv).a;
return float4(col, transparency);
}
ENDCG
}
}
}
Thanks in advance!


Thanks A LOT, I was searching for so long trying to find a solution!
– aouniaouniAlmost forgot something: I tried reducing the sigma (The quality gets a lot better) but if I want to change the blur amount with the kernel size slider the maximal value is ca. 25 (when the sigma lies between 0 and 10), after that the amount of blur stays the same. If I set the sigma to something like 100, I can put it even higher, but then I lose quality. Why is it like this?
– aouniaouni