Spawning objects around a circle

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

Hi guys,
the problem is: given a certain circle (e. g. 100 pixels), I need to spawn objects around its perimeter. Is there a certain method/type to do this dynamically?
I’m thinking of using a Vector2 and then spawn on its coordinates, but then I don’t know how to get the different coordinates of the perimeter (can i rotate the vector?).
I don’t know if it’s an obvious question, but I’m new to the engine :slight_smile:

:bust_in_silhouette: Reply From: Zylann

This is a simple math problem, that can be solved using sin and cos trigonometric functions + some angles:

var count = 10
var radius = 100.0
var center = Vector2(x, y)

# Get how much of an angle objects will be spaced around the circle.
# Angles are in radians so 2.0*PI = 360 degrees
var angle_step = 2.0*PI / count

var angle = 0
# For each node to spawn
for i in range(0, count):
	
	var direction = Vector2(cos(angle), sin(angle))
	var pos = center + direction * radius

	var node = scene_res.instance()
	node.set_pos(pos)
	parent.add_child(node)

	# Rotate one step
	angle += angle_step

I did not think about that, thanks!

DodoIta | 2017-02-27 19:20

Alternatively, you can just do it with vector rotation, avoiding the need for sin/cos :slight_smile:

var count = 10
var radius = Vector2(100, 0)
var center = Vector2(x, y)

var step = 2 * PI / count

for i in range(count):
    var spawn_pos = center + radius.rotated(step * i)

    var node = scene_res.instance()
    node.set_pos(spawn_pos)
    parent.add_child(node)

kidscancode | 2017-02-28 04:49

It works fine too, thanks! :slight_smile:

DodoIta | 2017-02-28 10:43

Thanks for your response! It was really helpful :slight_smile:

dogot42 | 2020-03-14 22:07