How to set Transparency gradually in a TextureRect?

Godot Version

v4.2.2 (installed at flathub)

Question

The next shader takes the position of the vertex and modifies the transparency of the pixel if it’s the distance between said pixel and the center (250, 250) is bigger than 63000.

The transparency itself should be set considering how far is the pixel from the center, being more transparent if the distance is bigger.

shader_type canvas_item;

varying float x;
varying float y;

varying float alp;
void vertex() {
	x = VERTEX.x - 250.0;
	y = VERTEX.y - 250.0;
}

void fragment() {
	alp = (x*x) + (y*y) - 63000.0;
	if (alp > 0.0) {
		COLOR.a = 1.0 - alp;
	}
}

However, at the moment that I run my project the program displays the TextureRect like this:

How should I do to set the transparency gradually?

1 Like

Alpha needs to be normalized between 0.0 and 1.0.

And all your values are well above 1.0, I don’t think a single pixel will be transparent with that math.

I was hoping to find a nice variable to do the normalization from the vertex position but there isn’t one show in the docs. You may need to do some fancy math in the vertex shader.

Which part of that screen do you want to fade, the blue box or the round one with the character?

The round one with the character! I forgot to mention it aaa

I kinda figured out tho! (or at least it kinda works as I wanted to)
I used SCREEN_PIXEL_SIZE in order to reduce the values of VERTEX
(where x = VERTEX.x / SCREEN_PIXEL_SIZE)

I finally figured out! The current shader is something like this:

shader_type canvas_item;

varying float x;
varying float y;

varying float alp;

void vertex() {
	x = VERTEX.x - 500.0;
	y = VERTEX.y - 500.0;
}

void fragment() {
	alp = ((x*x) * SCREEN_PIXEL_SIZE.y) + ((y*y) * SCREEN_PIXEL_SIZE.y);
	COLOR.a = (1.0 - (alp / 175.0)) * COLOR.a;
}

Here how the shader looks:
The shader’s off:


Now the shader on:

Thanks for the help!

1 Like

Oh good to see

I wanted to mention another route in using the UV’s of the texture rect to do the same thing, something like:

float remap(float value, float in_min, float in_max)
{
	return (value - in_min) / (in_max - in_min);
}

void fragment() 
{
	float fade_value = 1. - (distance(UV, vec2(.5,.5)) * 2.);
	fade_value = remap(fade_value, .05,.3);
	COLOR.a = mix(0.,1., fade_value);
}

Unless the UV’s are odd for the rect, this would be agnostic towards the placement and size of the rects.

The remap there is to take in a min/max for the fading edge to control it, which can be a parameter, for instance below is a large fade distance, then a shorter one that starts out past the middle. Adding a power function to this would further add some shape to the gradient.

1 Like

Ohh thanks a lot! I don’t know about UV so I didn’t even know how to use it :sweat_smile: I should read a bit more about glsl

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.