Create Node at random position in Area (3D)

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

In my game I wan the enemies to spawn at a random position in a circle around the player. How can I achieve that?

My attempt was to add a “Spawn”-Child to the player with following script (not working):

func _ready():
while true:
	var forward_dir :int= randi_range(0, 360)
	var amount:int = randi_range(12, 16)
	var enemy = preload("res://enemy.tscn").instantiate()
	get_node("/root/WorldScene").add_child.call_deferred(enemy)
	await enemy.ready
	enemy.look_at_from_position(global_position, Vector3(forward_dir,1,forward_dir))
	enemy.global_position.x += amount
	enemy.global_position.z += amount
	await get_tree().create_timer(1).timeout

→ not working, but I have to say I didn’t do much in 3D yet especially with something like this

:bust_in_silhouette: Reply From: CX97

You could create a random position in your world and normalize this vector (.normalized() gives it length of 1). This value you could multiply it with a random number from the inner spawn radius to the outer. Finally you give the enemy this random position + the player position.

func _ready():
     var player_position :Vector3 = $Player.global_position
     #just to get a random point in the world
     var enemy_position :Vector3 = Vector2(randf_range(-10, 10), 0, randf_range(-10, 10))
     #random number; defines how far from the player your enemy will spawn
     var enemy_distance = randf_range(MIN_RANGE, MAX_RANGE)
     enemy_position = enemy_position.normalized()
     #muliplies the random vector from the start with your radius
     enemy_position.x *= enemy_distance
     enemy_position.z *= enemy_distance
     var enemy = load("res://enemy.tscn").instantiate()
     $WorldScene.add_child(enemy
     #spawns the player at a position related to the player
     enemy.global_position = player_position + enemy_position

I hope my code will work for you, because I only tested it in 2D (but 3D is the same). I think there are more efficient ways to do what you want, but this is what I would do.