object random location

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

Hello, how can a city be built where all the buildings change their location after each execution, please help(3D)

:bust_in_silhouette: Reply From: njamster

After each execution of what? The game? A certain function?

But yeah, sure, just change the buildings position to random values:

const MIN = Vector3(-150, -100, -50)
const MAX = Vector3( 150,  100,  50)

func _ready():
    randomize() # change the random seed each time the programm runs

    for each building in get_tree().get_nodes_in_group("buildings"):
        # generates random float betweeen MIN_X|Y|Z and MAX_X|Y|Z
        var x = rand_range(MIN.x, MAX.x)
        var y = rand_range(MIN.y, MAX.y)
        var z = rand_range(MIN.z, MAX.z)

        # set the buildings position using the 3 random values
        building.position = Vector3(x, y, z)

Note: The code above assumes that all your buildings are already part of the scene and have been added to group called “buildings” (exactly like this, case-sensitive!).

Given how broad your question is, it’s quite possible that this is not what you want though. In which case I’d recommend you research “procedural generation” (which is vast and complicated area!) and come back with a more refined question.

Sorry im iranian im not good whrite english
I mean, when the game is running, the location of the objects is different from the next time the game is run.

abbos | 2020-09-26 13:38

I mean, when the game is running, the location of the objects is different from the next time the game is run.

Alright! Then the code I provided above does exactly that! For each building it generates three random numbers in a certain range and places the building a position in 3D space that is composed out of these three numbers. Because it does all of that in _ready it will only happen once: when the scene is loaded. Calling randomize() makes sure the numbers will be different when you run the game again.

njamster | 2020-09-26 13:55

Thank you brother

abbos | 2020-09-26 14:54