How do I turn a shader on and off via gdscript on a sprite?

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

I have a sprite and i am going to want to apply a shader to it when my mouse hovers over it. I have some working code for the shader, but I am stuck when it comes to turning it on and off at will. Is there some bit of code that allows me to target the shader in some sort of choice to have it ON or OFF as needed.

Thanks!

:bust_in_silhouette: Reply From: Inces

You can influence shaders code from GDScript by set_param() method
It will influence any shader variable introduced as uniform
So You can create uniform boolean variable in shader and calculate effect with it.
For example :

uniform float onoff hint_range(0.0,1.0)

void fragment{
         ALBEDO = mix(ALBEDO,vector4(1.0),onoff) }

this will switch color of object from original color to completely white

void vertex{
         VERTEX.y += 5.0 * sin(TIME) * onoff 

this will turn floating movement on and off

Sorry I’m fairly new to Godot and this is going over my head. Let’s say I have a sprite with this shader on:

shader_type canvas_item;

void fragment() {
    COLOR = texture(TEXTURE, UV);
    COLOR.a = abs(sin(TIME * 0.5));
}

But sometimes I’d want to turn the shader off, what gdscript could I use to disable the shader before turning it on again later at will?

Flying_cupcake | 2022-09-02 16:14

so your shader code can look like this :

shader_type canvas_item;
uniform float onoff ;

void fragment() {
    COLOR = texture(TEXTURE, UV);
    COLOR.a = mix(COLOR.a, abs(sin(TIME * 0.5)),onoff);
}

And your object can have this kind of code in script :

func on_mouse_hovered():
        $Sprite.material.set_shader_param("onoff",1)

func on_mouse_unhovered():
         $Sprite.material.set_shader_param("onoff",0)

Inces | 2022-09-03 18:08

Awesome this got me sorted thanks!

Flying_cupcake | 2022-09-03 21:55

1 Like

Great explanation, I used your tip. THANKS