How to create a simple Vignette Shader local to a sprite?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By Diet Estus

I am trying to create a simple Vignette Shader in Godot 3, adapting this tutorial.

For testing, I want to apply the Vignette to a sprite whose texture is Godot’s default icon.png.

So far I have:

shader_type canvas_item;
render_mode unshaded; // will output the shader opaquely


// resolution of the texture
uniform vec2 resolution = vec2(64, 64);

// fragment() runs on every pixel
void fragment (){

	// sample the texture
	vec4 tex_color = texture(TEXTURE, UV);

	// determine center of texture
	vec2 position = (FRAGCOORD.xy / resolution.xy) - vec2(0.5, 0.5);
	// determine length of current pixel to center of texture
	float len = length(position);

	// visualize length for debugging purposes
	COLOR = vec4(vec3(len), 1.0);


The output is:

enter image description here

The problem is that the effect is not limited to the Sprite, but is always local to the bottom left corner of the editor. I guess this is because GLSL uses the bottom left corner as origin and I’ve specified a resolution of 64x64. So, the center that’s being used in the shader is at (32, 32), assuming a bottom left origin.

My question is:

How do I adapt this so that the shader applies only to my Sprite, and not the whole screen?

I imagine I need to find the center of the sprite, then the distance of the current pixel/fragment from that center. But I don’t know how to do this.

:bust_in_silhouette: Reply From: SIsilicon

Your making this harder than it really is. Since your doing this relative to the sprite, use UV instead of FRAGCOORD and subtract vec2(0.5) to it. Its length shall give you the

void fragment() {
    float len = length(UV - vec2(0.5));

    COLOR = vec4(vec3(len, 1.0));

Thanks! I only just realized that UV is the coordinate within the texture. I thought it was something more complicated than that. Very new to shaders.

Diet Estus | 2018-05-06 19:10