Spawn childrens in random position from parent position

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

I’m making a space shooter game and I want more meteors to spawn when my player destroys a large one. But the children keep spawning in the same position instead of a random position of the parent position.

Here’s my code:

	extends Area2D

var pChilds := preload("res://Res/Scenes/Player/Meteor/MeteorSmall.tscn")
var pMeteorEffect := preload("res://Res/Scenes/Player/Bullet/MeteorEffect.tscn")

export var minSpeed: float = 10
export var maxSpeed: float = 20
export var minRotateRate: float = -30
export var maxRotateRate: float = 30
export var life: int  = 20

var playerInArea: Player = null
var speed: float = 0.0
var rotationRate: float = 0

func _ready():
	speed = rand_range(minSpeed, maxSpeed)
	rotationRate = rand_range(minRotateRate, maxRotateRate)
func _process(delta):
	if playerInArea != null:
func _physics_process(delta):
	rotation_degrees += rotationRate * delta
	position.y += speed * delta

func damage(amount: int):
	life -=  amount
	if life <= 0:
		var effect = pMeteorEffect.instance()
		var kid1 = pChilds.instance()
		var kid2 = pChilds.instance()
		var kid3 = pChilds.instance()
		effect.position = position
                    #I want this positions to be different 
		kid1.position = position
		kid2.position = position
		kid3.position = position
                    #So where the meteor is destroyed three meteors at different locations will be spawned
:bust_in_silhouette: Reply From: jgodfrey

You need to call randomize() once to ensure “randomness”. So, this should do it:


Oh, looks like I made an incorrect assumption here. I thought you were always getting the same random locations. But, looking at your code, that’s not the case - you’re just assigning the same position to all 3 new child nodes.

I assume you want the new nodes to be in the general vicinity of the just-destroyed node? In that case, you could just add some random vector to the destroyed node’s position for each new child’s position.

So, instead of this:

kid1.position = position
kid2.position = position
kid3.position = position

You could do something like this:

min_x = -5
min_y = -5
max_x = 5
max_y = 5
kid1.position = position + Vector2(rand_range(min_x, max_x), rand_range(min_y, max_y))
kid2.position = position + Vector2(rand_range(min_x, max_x), rand_range(min_y, max_y))
kid3.position = position + Vector2(rand_range(min_x, max_x), rand_range(min_y, max_y))

That’ll set the position of each child node to some random position from the original position. Just adjust the min/max values as needed.

jgodfrey | 2022-10-20 00:43

Thanks , it works perfectly now

AbDevTM | 2022-10-20 21:27