Shader radial gradient centered in sprite animation?

Hello there! I got a radial gradient working fine but I’m not sure how to make center of gradient in the center of sprite. Right now it takes the whole atlas as dimensions to center the gradient. As you can see in the video, 2 frames of animation have different gradients positions and not in their middle.


I’m using this atlas for testing:

And code in fragment:

varying mediump vec2 var_texcoord0;

uniform lowp sampler2D DIFFUSE_TEXTURE;
uniform lowp vec4 color1;
uniform lowp vec4 color2;

void main()
{
	vec4 base = texture2D(DIFFUSE_TEXTURE, var_texcoord0.xy);

	vec4 color1_blended = vec4(base.r * color1.r, base.g * color1.g, base.b * color1.b, color1.w);
	vec4 color2_blended = vec4(base.r * color2.r, base.g * color2.g, base.b * color2.b, color2.w);
	vec4 color1_final = vec4(color1_blended.rgb * color1_blended.a +  base.rgb * (1.0 - color1_blended.a), base.w);
	vec4 color2_final = vec4(color2_blended.rgb * color2_blended.a +  base.rgb * (1.0 - color2_blended.a), base.w);

	vec2 centered_pixel = var_texcoord0 - vec2(0.5);
	// Calculate distance from center (0.0 to ~0.7071 for corners)
	float dist = length(centered_pixel);
	// Normalize distance to [0.0, 1.0]
	float t = dist / 0.7071;

	base.rgba = mix(color1_final, color2_final, clamp(t, 0.0, 1.0));

	gl_FragColor = base;
}

I’m just starting with Defold and there are a lot of things I love about it. Hope some of you could find some time to guide me with this. Thanks in advance.

I’ve realized gradient isn’t clear enough. I uploaded with red (center) to white this time:

3 Likes

That solution worked like a charm!


Another thing I learnt today. Thank you very much.

3 Likes