Cloned child nodes are acting weirdly and unintended

Godot Version

4.2.2

Question

im a very begginer and was working with targets and childs but when a object spawn a children it start spining the parent and moving weirdly instead of the target


extends CharacterBody2D
var speed = 200
var timer = 500

func _physics_process(delta):
	var target
	var closest_distance = 9223372036854775807
	for node in get_tree().get_nodes_in_group("enemies"):
		var distance = global_position.distance_to(node.global_position)
		if distance < closest_distance:
			closest_distance = distance
			target = node

	if target:
		look_at(target.global_position)
		velocity = transform.x * speed
		move_and_slide()


func _process(delta):
	timer -= 1
	print(timer)
	if timer < 1:
		queue_free()
	if timer > 510:
		var clone = $".".duplicate()
		add_child(clone)
		timer -= 80
		pass	

func _on_area_2d_area_entered(area):
	if area.is_in_group("enemies"):
		timer += 80
		print("mitosis")
		pass

thanks you if you read this

children inherit their parent’s position and rotation, maybe you ment add_sibling? This will have the clones behave with their own position and rotation.

1 Like

thanks you so much, you save me :hearts:

As a note $"." is a slow way to get the self variable, which is inheritly used for method calls. for example self.duplicate() is the same as duplicate().

Getting the closest target every physics frame is very intense, you could give the characters a Timer node to re-target every half second for a big improvement. Another small improvement is using distance_squared_to instead of distance_to, this avoids the square root function which is taxing.