Cloned child nodes are acting weirdly and unintended

Godot Version



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:
		velocity = transform.x * speed

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

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

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.