Stop the enemy from following the player

Godot Version

godot 4.3

Question

hello guys well I'm new to godot and I have a problem my porblem is how we should stop the enemy when we look at it and when we look to other side the enemy follows the player again just like scary games but instead in topdown 2d I would be happy if you guys help me thanks

Depending on 2d or 3d… here’s something to tinker about

func _physics_process(delta):
    if not player:
        return
        
    # Calculate direction to player
    var direction_to_player = global_position.direction_to(player.global_position)
    var distance_to_player = global_position.distance_to(player.global_position)
    
    # Check if player is in range
    if distance_to_player <= player_detection_range:
        # Get the player's forward direction (assuming it's stored in a variable)
        var player_direction = Vector2.RIGHT.rotated(player.rotation)
        
        # Calculate angle between player's forward direction and direction to enemy
        var angle_to_enemy = rad_to_deg(player_direction.angle_to(-direction_to_player))
        
        # Check if player is looking at enemy
        is_being_watched = abs(angle_to_enemy) <= view_angle_threshold
        
        if not is_being_watched:
            # Move towards player when not being watched
            velocity = direction_to_player * move_speed
        else:
            # Stop moving when being watched
            velocity = Vector2.ZERO
    else:
        # Stop moving when player is out of range
        velocity = Vector2.ZERO
    
    move_and_slide()
1 Like

Thanks for your help