my random function is broken

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

I have a ball object I want when the game starts to randomly choose a direction (right or left) by this code:

var first_dir

 func _ready():
	first_dir =  round(rand_range(0, 1))
	if first_dir == 0:
		first_dir = -1

but every time I start the game it goes right so I decided to print firts_dir
and the result always started with:

1
1
-1
-1
-1
-1

so what can I do

:bust_in_silhouette: Reply From: spaceyjase

It’s working properly:

tl;dr

func _ready():
    randomize() # add this
    first_dir =  round(rand_range(0, 1))
    if first_dir == 0:
        first_dir = -1

Indeed, without randomize(), the pseudo random RNG will be deterministic (always the same)

godot_dev_ | 2023-05-31 13:30