Why doesn't work this code ? ( Shader programming)

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By rpggeek
shader_type canvas_item;

void vertex(){
	
}

void fragment(){
	float amk=0.0;

	amk = amk + 0.1;
	
	COLOR = texture(TEXTURE,UV+amk);
}

What i want to do is that to make my texture swite right or left continuous.But it works 1 time.
Why doesn’t increase ‘amk’ variable ?

:bust_in_silhouette: Reply From: Zylann

Because the fragment() function runs for every single pixel of the screen. Also, amk is a local variable, it won’t be remembered between two calls anyways.

In shaders there is also no way to assign a member variable, that’s not how shaders work. The reason is they run on your graphics card, and executed multiple times in parallel. There is no room for shared state.

Finally, UV + amk is not what you want. UV is a vec2, and amk is a single number. Which means it will probably add the same number to both X and Y, and your texture will scroll in diagonal, not left and right.

What you need to use is either use a uniform parameter which you set from script every frame, or the TIME parameter (which is also a uniform behind the scenes).

shader_type canvas_item;

void fragment(){
    COLOR = texture(TEXTURE, UV + vec2(TIME, 0));
}

Also make sure your texture has the Repeat flag checked, otherwise the texture won’t repeat.

I stronly recommend you read all of this Shaders — Godot Engine (stable) documentation in English

Hi thanks for answer, but the code you wrote work like this,the picture doesn’t move continuously.
Also i couldn’t find anything about the “TIME” parameter in the docs.
Sorry but i’m totally noob to shaders.

rpggeek | 2020-03-30 00:49

It moves normally in the test project I made for it, one repetition per second. With your code, it barely moves because the multiplier 0.0001 makes the animation so slow it cannot be seen. The “change” you are seeing with that multiplier is irrelevant.

The stretching shown in your screenshot indicates that you haven’t enabled repetition in your import settings.
Click on your texture in the File Explorer, then go to the Import tab, Flags → Repeat → Enabled.

Zylann | 2020-03-30 00:59

Yep,did it and works perfecly,thank you !

rpggeek | 2020-03-30 01:05