Detect CollsionBody2D before spawning

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

I have an energy orb that spawns at random locations, before that, a monster detector spawns at that random location to tell if there is monsters or not, if monsters was found, then find another random location for the spawn.

RayCast2D won’t help because the monsters move at random speed, i want to detect them in another way, can you help?

:bust_in_silhouette: Reply From: Magso

Assign all the monsters to a group and create an array.

func _ready():
    allMonsters = get_tree().get_nodes_in_group("Monsters")

Then use distance_to in a for loop

for count in allMonsters.size():
    if spawnNode.distance_to(allMonsters[count].get_global_pos()) < desiredDistance:
        #find another location

It gives me an error Invalid get index ‘[RigidBody2D:1684]’ (on base: ‘Array’).
i’m not sure what’s the reason…

soulldev | 2019-04-19 10:36

That’s peculiar, I’ve got the same error and it seems to be the for loop but I’m not sure why that is. The error doesn’t happen with a while loop.

while count < allMonsters.size():
	if spawnNode.distance_to(allMonsters[count].get_global_pos()) < desiredDistance:
		#find another location
	count += 1
#Reset the count int
count = 0

also if distance_to causes an error try spawnNode.transform.origin.distance_to...

EDIT: I completely missed that it needs .size()

for count in allMonsters.size():

Magso | 2019-04-19 12:26