Created
December 31, 2024 18:42
-
-
Save statico/3a54fbbf2b59e1f0543bf7e287b86166 to your computer and use it in GitHub Desktop.
parallax starfield in Godot 4
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@tool | |
extends ParallaxBackground | |
@export | |
var star_colors: Array[Color] = [Color(1, 1, 1, 1), Color(0.8, 0.8, 1, 1), Color(1, 0.8, 0.8, 1)] | |
@export_range(10, 500) var num_stars_per_layer: int = 300 | |
@export_range(0.1, 2.0) var twinkle_frequency: float = 2.0 | |
@export var parallax_speeds: Array[float] = [0.1, 0.3, 0.6] | |
var viewport_size: Vector2 | |
var stars: Array[Array] = [] | |
var twinkle_times: Array[Array] = [] | |
func _ready() -> void: | |
viewport_size = get_viewport().get_visible_rect().size | |
# Create three parallax layers | |
for i in range(3): | |
var parallax = ParallaxLayer.new() | |
parallax.motion_scale = Vector2(parallax_speeds[i], parallax_speeds[i]) | |
add_child(parallax) | |
# Create stars for this layer | |
var layer_stars = [] | |
var layer_twinkle_times = [] | |
for _j in range(num_stars_per_layer): | |
var star = ColorRect.new() | |
star.size = Vector2(2, 2) | |
star.position = Vector2( | |
randf() * viewport_size.x * 2 - viewport_size.x, | |
randf() * viewport_size.y * 2 - viewport_size.y | |
) | |
star.color = star_colors[randi() % star_colors.size()] | |
parallax.add_child(star) | |
layer_stars.append(star) | |
layer_twinkle_times.append(randf() * twinkle_frequency) | |
stars.append(layer_stars) | |
twinkle_times.append(layer_twinkle_times) | |
func _process(delta: float) -> void: | |
# Update star twinkle effect | |
for layer_idx in range(stars.size()): | |
for star_idx in range(stars[layer_idx].size()): | |
twinkle_times[layer_idx][star_idx] -= delta | |
if twinkle_times[layer_idx][star_idx] <= 0: | |
var star = stars[layer_idx][star_idx] | |
star.color.a = randf_range(0.3, 1.0) | |
twinkle_times[layer_idx][star_idx] = randf() * twinkle_frequency |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment