I am making a rogue-like game in Godot. Currently, I am stuck with the world generation. I know how to add children, but I am wondering if there is a way to add those children in a specific position. I also need to know how to add nodes to an array, and then choose one from the array to spawn.
1 Answer
Placing Nodes from code
To change the position you need to…
- For a Node2D set the
position
ortransform2D
. - For a Control set the
rect_position
(callset_position
). - For a Node(3D) set the
transform
.
If you have a Node
(scene loaded and instantiated) you want to add to the scene, you can do that before you call add_child
on the pregnant future parent Node
.
Adding and removing from arrays
To add an element to an Array
, you can call on the Array
either push_back
(adds at the end, alias: append
), push_frost
(adds at the beginning), or insert
(adds at the specified position).
To remove, you have pop_back
(removes from the end, returns the value, null when empty), pop_front
(remove from the beginning, returns the value, null when empty) and remove
(removes at a given position, no return). You also have erase
to remove by value instead of position. And clear
to remove all.
To access an item (to read it or write to it with assignment) you can use square brackets (e.g. array[2]
).
On the ways to use arrays and scene nodes
If you want to make a Node
pool, you can treat the Array
as a queue. Pushing at one end and popping form the other. When you need an object, pop, if null create a new one. When you no longer need an object, push.
If you are making an Array
for the objects that are in the scene… There is no need. You can add to the scene with add_child
, remove with remove_child
, get by index with get_child
and so on.
Although, there is value in working with other structures such as a Dictionary
or a multidimensional array (There are no true multidimensional arrays in GDScript, only jagged arrays (arrays within arrays, just like these parenthesis), but there are in C#), there are also third party oct and quad tree solutions.
To randomize your Array
, call shuffle
on it. For example, you could make an Array
of Node
that you will add, shuffle it, and then add them one by one in the resulting order.
There is also a RandomNumberGenerator
type you could find useful in GDScript. For example, you could have an Array
of PackedScene
(scenes loaded, but not instantiated), and use the random number generator (call randi_range
) to pick which to instantiate (or use a pool here) and then add to the scene. Don't forget to call randomize
on the RandomNumberGenerator
to seed it (this is usually done in _ready
).