How do I make a node spawn at a certain length in a random direction from another node?

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

Im making a game in which when you cut down a tree, a log spawns around 15 pixels away from the tree root in a random direction. I cannot figure out how would this be done, can anyone please help?

:bust_in_silhouette: Reply From: crossbito

Hi, something like this?

//inside tree spawn
get_tree().add_child(log)
var rng = RandomNumberGenerator.new()
var randX = rng.randi_range (-15, 15);
var randY = rng.randi_range (-15, 15);

//global position used in vector2 has to be the position of the tree
log.global_position = Vector2(global_position.x+randX,global_position.y+randY );

I apologize if there are any misspellings in the code. I don’t have the editor at hand to test it.

Hi, if I understand this code correctly, it will spawn a log inside a square that’s 15x15 around the central node
Correct me if I’m wrong my knowledge is a bit limited on subject of the Vector2

However, if what I said is true; it’s not what I want.
You can imagine it like this; you have a central node and then a circle around it with a radius of 15, and you need a log to spawn on the edge of that circle

1Milan1 | 2023-06-06 19:20

Aah, yes, I got it wrong. In that case, because I’m lazy, I would move the pivot point of a Spawn log (a node I would create) on the X axis by 15 pixels(the pivot point has to be inside the tree at 0,0). Then, I would rotate it from 0 to 360 degrees and spawn the actual log in the correct position of a node within the spawner. It may seem strange, but I like to do these types of things because then I can copy the spawn and reuse it without touching the code.

crossbito | 2023-06-06 21:32

:bust_in_silhouette: Reply From: 1Milan1

I found out it’s possible to calculate the x and y coordinates of the logs using this:

log.position.x = tree.x + circle_radius * cos(random_angle)
log.position.y = tree.y + circle_radius * sin(random_angle)

where random_angle is described in radians
hopefully it comes of use to someone else in the future <3