Godot Version
4.2
Question
I found the following shader on GodotShaders, but don’t quite understand the math of the rand function. It creates a great starfield, but I would like to slowly scroll it when my ship is moving, to help illustrate motion.
Does anyone understand it enough to help me with scrolling? I have added variables for the camera and it’s impact (would like to have a slow scroll like a parallax bg). But, any changes I have tried to offset position end up with disappearing stars or other unwanted results.
shader_type canvas_item;
uniform vec2 camera_pos;
uniform float camera_translation_factor = 0.1;
uniform vec4 bg_color: source_color;
float rand(vec2 st) {
vec2 key = vec2(12.9898,78.233);
float multiplier = 43758.5453123;
return fract(sin(dot(st.xy, key)) * multiplier);
}
void fragment() {
float star_size = 30.0;
float prob = 0.99;
vec2 camera_impact = floor(camera_pos * camera_translation_factor);
vec2 pos = floor(1.0 / star_size * FRAGCOORD.xy);
float color = 0.0;
float starValue = rand(pos);
if (starValue > prob)
{
// Big stars
vec2 center = star_size * pos + vec2(star_size, star_size) * 0.5;
float t = 0.9 + 0.2 * sin(TIME * 8.0 + (starValue - prob) / (1.0 - prob) * 45.0);
color = 1.0 - distance(FRAGCOORD.xy, center) / (0.5 * star_size);
color = color * t / (abs(FRAGCOORD.y - center.y)) * t / (abs(FRAGCOORD.x - center.x));
}
else if (rand((SCREEN_UV.xy) / 20.0) > 0.996)
{
// Little stars
float r = rand(SCREEN_UV.xy);
color = r * (0.85 * sin(TIME * (r * 5.0) + 720.0 * r) + 0.95);
}
COLOR = vec4(vec3(color), 1.0) + bg_color;
}