system
February 18, 2019, 3:26pm
1
Attention
Topic was automatically imported from the old Question2Answer platform.
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!

system
February 18, 2019, 5:26pm
2
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

system
October 6, 2022, 9:46pm
3
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