What is the best way to generate a random boolean, i.e. 0 or 1?

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

I want to generate a random boolean to select random direction of rotation (for an asteroid if you’re interested :slight_smile: )

:bust_in_silhouette: Reply From: kidscancode

You could do something like this:

var dir = true
if randi() % 2:
    dir = false    

On the other hand, if you’re looking for a random rotation direction, then what you really want is either 1 or -1, which you can get if you raise -1 to a random power of 0 or 1.

var random_dir = pow(-1, randi() % 2)

Or (randi() & 2) - 1, if you need either -1 or 1.
If you only need 0 or 1, just randi() & 1.

Zylann | 2020-01-18 21:36

:bust_in_silhouette: Reply From: LeoDog896

You can do:

var choice = randi() % 2 == 0
1 Like
var choice: bool = randi() & 1
var choice := bool(randi() & 1)

var choice: bool = randi_range(0, 1)
var choice := bool(randi_range(0, 1))