Why my enemy isn't moving towards the initial position, and how should I do it?

Godot Version

4.2

Question

So, I have an Enemy that follows a 2d Path and when it encounters with the player starts following the player. But when the player leaves the range of the enemy I want it to go back to original position and then start the path again. But I don’t know exactly how to make so that the enemy moves toward the initial position.

This is what I did so far:

extends EnemyState
class_name EnemyPatrol

@onready var Pathing = get_ancestor(3)
@onready var initial_position = enemy.global_position

var patrol_speed = 50
var can_patrol = true

# Virtual function. Called by the state machine upon changing the active state. The `msg` parameter
# is a dictionary with arbitrary data the state can use to initialize itself.
func enter(_msg := {}) -> void:
	print_debug("Patrol")
	can_patrol = false
	


# Virtual function. Corresponds to the `_physics_process()` callback.
func physics_update(delta: float) -> void:
	if enemy.global_position != initial_position and not can_patrol:
		enemy.global_position.move_toward(initial_position, patrol_speed * delta)
	else:
		Pathing.progress += patrol_speed * delta
		can_patrol = true


func _on_detection_area_area_entered(area):
	if area.is_in_group("Player"):
		get_ancestor(2).player = area.get_parent()
		transitioned.emit("chase")

I’m using a state machine, so this would be the Patrol state (the state machine is working fine, so thats not the problem).

You need to assign the global_position back when doing enemy.global_position.move_toward()

enemy.global_position = enemy.global_position.move_toward(initial_position, patrol_speed * delta)
1 Like

Oh such a easy mistake, thank you very much!

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.