Enemy Patrol Not Reversing Direction

Godot Version

GODOT4

Question

Hi there! So I’ve been running into a problem with having an enemy patrol. The enemy is supposed to keep walking until it hits a wall, reverse direction, and continue the process. Instead, it just turns around on it’s own, without a timer or anything attached.

ezgif-4-02255f23f1

Currently, an enemy node has a Node2D connected to, and it has this script:

#Patrol
extends Node2D

@onready var _character: Character = get_parent()
@onready var _floor_ray : RayCast2D = $RayCast2D
@onready var position_var : int = 20
@onready var _patrol_speed : int = 30
var _direction : float

func _ready():
	_direction = -1 if _character.is_facing_left() else 1

func _process(_delta : float):
	if _character.is_on_wall():
		_direction = sign(_character.get_wall_normal().x)
		print("Position Updated")
	_character.run(_direction)

The enemy has it’s own script of course, and this is the relevant chunk:

#Enemy
func _physics_process(delta : float):
	if not _is_facing_left && sign(_direction) == -1:
		face_left()
	elif _is_facing_left && sign(_direction) == 1:
		face_right()
	if is_on_floor():
		_ground_physics(delta)
	else:
		_air_physics(delta)
	_was_on_floor = is_on_floor()
	move_and_slide()

func run(direction : float):
	if _is_dead || _is_attacking:
		_direction = 0
	else:
		_direction = direction

If you need more information or clarification please let me know :slight_smile:

Cannot reproduce this. That being said, you left a lot of stuff out (like the content of your functions face_left, face_right, _ground_physics, air_physics, as well as any usage of _floor_ray, position_var and _patrol_speed).

1 Like