I am facing problem in my first project, please help me

Godot Version

godot 4.3 stable

Question

when player enters the enemy’s area2d from right side it goes to opposite direction of plyer instead to the player and i have also set the enemy to stop but it doesn’t stop when reaching player please help me
code:
extends CharacterBody2D

var speed = 40
var player_chase = false
var player = null
var stop_distance = 10 # Minimum distance to stop chasing the player

func _physics_process(delta):
if player_chase and player:
var direction = player.position - position
var distance = direction.length()

	if distance > stop_distance:
		# Move towards the player if beyond stop_distance
		position += direction.normalized() * speed * delta
		$AnimatedSprite2D.play("walk")
		
		# Flip sprite based on player's relative position
		if player.position.x < position.x:
			$AnimatedSprite2D.flip_h = true
		else:
			$AnimatedSprite2D.flip_h = false
	else:
		# Stop moving when close enough to the player
		$AnimatedSprite2D.play("idle")
else:
	$AnimatedSprite2D.play("idle")

func _on_area_2d_body_entered(body: Node2D) → void:
player = body
player_chase = true

func _on_area_2d_body_exited(body: Node2D) → void:
if body == player:
player = null
player_chase = false

Try to include some print() statements first in your signal handling functions (the last 2) to make sure the signals are firing correctly.

it is still not working like it should be, it is still going away from player when going to right side

This was not supposed to fix your problem, but to allow you to better debug it - i.e. check where the code propagates for each of the states and if this matches your expectations.

If you still can’t resolve the problem, share your findings here and then we can try to debug where the problem lies exactly.

It looks like you flip the sprite but you still use the same code. So the travel direction isn’t flipped.

Use the code tag </> when posting code here so that it is formatted properly.

1 Like