How do I spawn objects in the world at specific places.

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By crabcrabcam
:warning: Old Version Published before Godot 3 was released.

Here’s my code

I’m making a Skiing game and I need to spawn an infinite load of the snow I have. It’s under a single node. I’ve looked at the Flappy Bird code but it just says to add_child(tube). That doesn’t say where to put the object. How can I set the position so that it is always exactly under the last one?

Then I need to set the flags for the player to go through (like flappy bird except they get closer together) I have a World node with a script I think I should use to control all this. I was going to have an overall node for “flags”, spawn that in and then move the flags as far apart from the centre (where the overall node will sit) as they should be for the current difficulty.

So the flags will be a set distance from each other, but it will change the higher the players score, and at the same time they will be in a random distance but can’t be off the screen on either side. I’m not quite sure how I’d do this.

It’s probably something really stupid I’m not thinking of but thanks for help in advance :slight_smile:

In order to control the node’s position before placing it(or after) you can use this:

var nodeInstance = node.instance()
nodeInstance.set_pos(//Vector2 position)

that way the instance position of the node is set to something you decide and not (0,0)…

rustyStriker | 2017-05-07 12:24

Ah thanks. Is that relative to what the parent is or to the overall world?

crabcrabcam | 2017-05-07 14:13

:bust_in_silhouette: Reply From: eons

Just use the same x (global) position value for the next one.


Since Flappy Bird has always 2 tubes you can make a scene with both, just a single body with 2 sprites and shapes or 2 tube scenes with the separation they need.
Then only change the Y position of the dual tube scene.

:bust_in_silhouette: Reply From: rredesigns

If it is like Flappy Bird, then you can create your flag posts in pairs (just like the tubes), and then make them spawn randomly between certain values.

I don’t remember if Godot has a random() method, but it’s almost sure it does, just pick a random value for spacing in X and a random height for Y. So you can keep an accumulator for X.

onready var flagPacked = preload("res://assets/flag.tscn")

#######

var flagPrev = Vector2() # Give here a good starting value.
var flag = flagPacked.instance()

var newPos = Vector2(flagPrev.x + rand(5, 9), rand(30, 50)) # This here sets pos based on the previous X value.

##########################

flag.set_pos(newPos)
flagPrev = newPos #Update the previous in each flag spawn.

get_tree().get_root().add_child(flag)