[Godot 3.0/3.1]how to make a random number in shader?

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

how to make a random number in shader?

I cannot see any random related built-in in Godot shader doc.
Does it mean that it is impossible to make random number in shader?

Or I am missing something?

Thanks!

:bust_in_silhouette: Reply From: TheFamousRat

Hello Icqqq,

There aren’t any built-in rand functions (or equivalent) in the godot shaders, but you can use a function like that

    float rand(vec2 co){
    return fract(sin(dot(co.xy ,vec2(12.9898,78.233))) * 43758.5453);
}

Source

This is useful to link a coordinate (or a pair of numbers) to a seemingly random number float. But if you need to have a random number and don’t know what to send to this function, a rand(vec2(TIME,0.0)) should do the trick

:bust_in_silhouette: Reply From: LudditeGames
float random( vec2 p )
{
   // e^pi (Gelfond's constant)
   // 2^sqrt(2) (Gelfond–Schneider constant)
     vec2 K1 = vec2( 23.14069263277926, 2.665144142690225 );

   //return fract( cos( mod( 12345678., 256. * dot(p,K1) ) ) ); // ver1
   //return fract(cos(dot(p,K1)) * 123456.); // ver2
     return fract(cos(dot(p,K1)) * 12345.6789); // ver3
}

The other random number generator wasn’t as random as I liked, this stack overflow answer was helpful for me: hlsl - Can I generate a random number inside a pixel shader? - Stack Overflow