- Home /
Getting horizontal gradient in unlit sprite shader even sprite is rotated
Hello,
I am writing a basic unlit sprite shader that creates gradient between 2 colors. I achieved that easily with lerping the value with UV's y coordinate. But with that way, when I rotate my sprite, gradient is rotating with sprite, as expected. Lerping the value with pixel's world space position's y value solved rotation problem, but only if sprite is at the center of the world. When sprite is moved to different position in world, gradient value is changing. I want to achieve gradient is horizontal all the time and only happening inside sprite boundaries. How can write that with using fragment shader?
Current state of my shader:
Shader "Custom/SpriteGradient"
{
Properties
{
_MainTex ("Main Texture", 2D) = "white" {}
_TopColor ("Top Color", Color) = (1, 1, 1, 1)
_BottomColor ("Bottom Color", Color) = (1, 1, 1, 1)
[Toggle(BLEND)] _Blend("Blend With Texture", Float) = 0
}
SubShader
{
Pass
{
Blend SrcAlpha OneMinusSrcAlpha
CGPROGRAM
#pragma vertex vert
#pragma fragment frag
#pragma shader_feature BLEND
#include "UnityCG.cginc"
struct vertexIn {
float4 pos : POSITION;
float2 uv : TEXCOORD0;
};
struct v2f {
float4 pos : SV_POSITION;
float2 uv : TEXCOORD0;
};
fixed4 _TopColor, _BottomColor;
sampler2D _MainTex;
fixed4 _MainTex_ST;
float4x4 _TextureRotation;
v2f vert(vertexIn input)
{
v2f output;
output.pos = UnityObjectToClipPos(input.pos);
output.uv = input.uv;
output.worldPos = mul (unity_ObjectToWorld, input.pos);
output.screenPos = ComputeScreenPos(input.pos);
return output;
}
fixed4 frag(v2f input) : COLOR
{
float2 screenUV = input.screenPos.xy / input.screenPos.w;
//float currentY = input.worldPos.y;
//float4 centerY = mul(unity_ObjectToWorld, float4(0.5,0.5,0.0,1.0)).y;
fixed4 textureColor = tex2D(_MainTex, input.uv);
fixed4 gradientValue = lerp(_BottomColor, _TopColor, input.uv.y);
textureColor.rgb *= textureColor.a;
#ifdef BLEND
textureColor.rgb *= gradientValue;
#else
textureColor.rgb = gradientValue.rgb;
#endif
return textureColor;
}
ENDCG
}
}
}
This is the state where I get graient value by using UV.y . Actually, finding center position is easy. If there is some built-in function that can give world position of the highest and lowest pixel position at Y axis correctly (even sprite is rotated upside down), I guess I can lerp using those values.
Any help would be greatly appreciated. I am new to shader coding.
Thank you all.
Your answer
Follow this Question
Related Questions
Adding normal map to Sprite shader 1 Answer
Outline set of tiled sprites 0 Answers
Render sprite only on top of a specific sorting layer 1 Answer
Sprite Renderer Missing Material after running 1 Answer
Sprite Shader not working in 5.6 0 Answers