+1 vote

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 :)

in Engine by (515 points)

1 Answer

+1 vote
Best answer

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
by (27,897 points)
selected by

I did not think about that, thanks!

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

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)

It works fine too, thanks! :)

Thanks for your response! It was really helpful :)

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.