Ok so I have a game, where you can place different units, then there is meant to be an enemy that will go to the position of the unit. For some odd reason, the enemy stops at the top left of the unit and not at the unit itself. Here is my enemy code:
extends Node2D
@export var body: CharacterBody2D
@export var animationplayer: AnimationPlayer
@export var speed: float = 100.0 # Speed at which the enemy moves
@export var stop_distance: float = 10 # Distance at which the enemy stops moving towards the target
@export var collision_shape: CollisionShape2D # Assign the CollisionShape2D node from the enemy scene
var target: Node = null
# Selects a random target from the "targets" group
func select_random_target():
var targets = get_tree().get_nodes_in_group("targets")
if targets.size() > 0:
target = targets[randi() % targets.size()]
print("New target selected: ", target.name)
else:
target = null
print("No targets available")
func _process(delta):
if body != null:
if target == null:
select_random_target() # Continuously check for a target
if target != null:
print("Enemy Position:", position)
print("Target Position:", target.global_position)
var distance_to_target = position.distance_to(target.global_position)
print("Distance to Target:", distance_to_target)
if distance_to_target > stop_distance:
position = position.move_toward(target.global_position, delta * speed)
else:
print("Reached target.")
all of the sprites and collsions are at 0,0. I am using a node specifically for the enemy ai. the node tree is Node2d: Enemy > Node2d: ai > Characterbody2d > Sprite2D, CollisionShape2D
It would help to have images of the scene tree and the objects positions in it. Maybe post the player’s scene and the level’s scene. Your code is correct, one addition could be to use the enemies global_position, this will help unless it, or the player’s children are offset.
var distance_to_target = global_position.distance_to(target.global_position)
print("Distance to Target:", distance_to_target)
if distance_to_target > stop_distance:
global_position = global_position.move_toward(target.global_position, delta * speed)
else:
print("Reached target.")
ah, it must be offset then because that seems to fix it, weird as all the nodes are at 0,0. I used this code in another project and it worked fine. well thank you so much for the fix, I was trying to wrap my head around it for a while lol