0 votes

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

in Engine by (180 points)

1 Answer

+1 vote
Best answer

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.

by (10,467 points)
selected by

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.

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.

Thank you brother

Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to webmaster@godotengine.org with your username.