- Home /
2D Sprite Shader Acting like Light
Hi again!
I'm tyring to create a shader for Sprites that acts like a light, I have almost done what I wanted to do but there is a catch.
If I want to decrease or increase the intensity of the light I have to use the color of the sprite it self (in this case, the alpha channel) but if I want to make it really bright, I have duplicate the sprite, because the alpha is clamped from 0 to 1 and even if I replaced it with my out float slider it will still be clamped from 0 to 1. I wanted to have a property that would increase the intensity of this effect without having to duplicate sprites.
Here I'm increasing the intensity using the Alpha channel of the color. but 255 is the maximum
Because 255 is maximum, I have to duplicate Sprites
Heres what I have so far:
Shader "2D Light"
{
Properties
{
[PerRendererData] _MainTex ("Sprite Texture", 2D) = "white" {}
_Color ("Tint", Color) = (1,1,1,1)
[MaterialToggle] PixelSnap ("Pixel snap", Float) = 0
[PerRendererData] _AlphaTex ("External Alpha", 2D) = "white" {}
}
SubShader
{
LOD 0
Tags { "Queue"="Transparent" "IgnoreProjector"="True" "RenderType"="Transparent" "PreviewType"="Plane" "CanUseSpriteAtlas"="True" }
Cull Off
Lighting Off
ZWrite Off
Blend DstColor DstAlpha
Pass
{
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma target 3.0
#pragma multi_compile _ PIXELSNAP_ON
#pragma multi_compile _ ETC1_EXTERNAL_ALPHA
#include "UnityCG.cginc"
struct appdata_t
{
float4 vertex : POSITION;
float4 color : COLOR;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
};
struct v2f
{
float4 vertex : SV_POSITION;
fixed4 color : COLOR;
float2 texcoord : TEXCOORD0;
UNITY_VERTEX_INPUT_INSTANCE_ID
UNITY_VERTEX_OUTPUT_STEREO
};
uniform fixed4 _Color;
uniform float _EnableExternalAlpha;
uniform sampler2D _MainTex;
uniform sampler2D _AlphaTex;
v2f vert( appdata_t IN )
{
v2f OUT;
UNITY_SETUP_INSTANCE_ID(IN);
UNITY_INITIALIZE_VERTEX_OUTPUT_STEREO(OUT);
UNITY_TRANSFER_INSTANCE_ID(IN, OUT);
IN.vertex.xyz += float3(0,0,0) ;
OUT.vertex = UnityObjectToClipPos(IN.vertex);
OUT.texcoord = IN.texcoord;
OUT.color = IN.color * _Color;
#ifdef PIXELSNAP_ON
OUT.vertex = UnityPixelSnap (OUT.vertex);
#endif
return OUT;
}
fixed4 SampleSpriteTexture (float2 uv)
{
fixed4 color = tex2D (_MainTex, uv);
#if ETC1_EXTERNAL_ALPHA
fixed4 alpha = tex2D (_AlphaTex, uv);
color.a = lerp (color.a, alpha.r, _EnableExternalAlpha);
#endif
return color;
}
fixed4 frag(v2f IN ) : SV_Target
{
fixed4 c = SampleSpriteTexture (IN.texcoord) * IN.color;
c.rgb *= c.a;
return c;
}
ENDCG
}
}
}