0 votes

Hi guys,
I created a script that spawn 10 objects at the start of the game in random location.

extends Node2D

var n = 10
var object = load("res://Object.tscn")

func _ready():

func spawn():
    for i in n:
        var x = rand_range(0,300)
        var y = rand_range(0,300)
        var rand_pos = Vector2(x,y)

        var object_instance = object.instance()
        object_instance.position = rand_pos

How can I make sure that all of the objects are a certain distance from each other?
I want to leave a minimum distance between them.
Any help will be appreciated, thanks

Godot version Godot 3.2.3
in Engine by (12 points)

2 Answers

0 votes

You could use a range [1, 10[, multiply by 30, and add a random [-5, 5]. This leaves you with a minimum distance of 20, without the placement grid being too apparent.
Also store the position of previously placed items to not select the same spot twice.

by (2,484 points)

Sorry could you be a little more specific? I can't quite understand what you mean.

can you be more specific please

0 votes

You can use an Array object to save the data of distance~

by (36 points)
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.