i tried using another node to do it and it worked but the characterbody2d just cant do it. it seems to have an issue with the clones position part of the code.
script:
extends CharacterBody2D
var speed = 50
var target
var direction
var health = 100
var hunger = 100
var energy = 100
var maxspeed = 50
var oldtarget
var child_path = preload(“res://herbivore.tscn”)
func _ready() → void:
print(“Child path is:”, child_path)
print(“Is PackedScene?”, child_path is PackedScene)
direction = (position - global_position).normalized()
direction.x += randf_range(-0.3, 0.3)
direction.y += randf_range(-0.3, 0.3)
direction = direction.normalized()
func _physics_process(delta: float) → void:
if target:
direction = (target.position - position).normalized()
velocity = direction * speed
else:
velocity = direction * speed
energy -= speed * 0.001
speed = 50 * (energy * 0.01)
speed = clamp(speed, 0, maxspeed)
if hunger < 20:
health -= 0.1
$Label2.text = "health:" + str(health)
health = clamp(health, -1, 100)
$Label3.text = "energy:" + str(energy)
energy = clamp(energy, -1, 100)
if health < 0:
queue_free()
if energy < 30:
if energy < 15:
health -= 2
else:
health -= 0.5
if health < 40 and energy > 50:
energy -= 1
health += 1
$Label4.text = "speed:" + str(speed)
move_and_slide()
func _on_area_2d_body_entered(body: Node2D) → void:
if body.is_in_group(“attractors”):
if target:
oldtarget = target
target = body
if oldtarget:
var oldlenghth = position.distance_to(oldtarget.position)
var lenghth = position.distance_to(target.position)
if lenghth < oldlenghth:
oldtarget = null
else:
target = oldtarget
oldtarget = null
func hurt(damage : float):
health -= damage
func _on_area_2d_2_body_entered(body: Node2D) → void:
if body.is_in_group(“attractors”):
body.hurt(0.8)
hunger += 1
hunger = clamp(hunger, -1, 100)
$Label.text = “stomach:” + str(hunger)
energy += 2
func _on_hunger_timeout() → void:
hunger -= 1
$Label.text = “stomach:” + str(hunger)
hunger = clamp(hunger, -1, 100)
func _on_timer_timeout() → void:
if target == null:
direction = (position - global_position).normalized()
direction.x += randf_range(-0.3, 0.3)
direction.y += randf_range(-0.3, 0.3)
direction = direction.normalized()
func _on_timer_2_timeout() → void:
if energy > 50 and hunger > 40:
var child = child_path.instantiate()
if child == null:
print(“ERROR: instantiate() returned null!”)
return
print(“Instantiated node type:”, child.get_class_name())
child.position = position + Vector2(randf_range(-5, 5), randf_range(-5, 5))
child.hunger = hunger * randf_range(0.8, 1.2)
child.maxspeed = maxspeed * randf_range(0.8, 1.2)
child.speed = speed * randf_range(0.8, 1.2)
get_tree().current_scene.add_child(child)
energy -= 40
hunger -= 20