Godot 3d: How to make NPC AI go to target and attack? (Using raycast and state_machine)

Godot Version

Godot-4

Question

I need to make the two things below happen with Raycast but I’m struggling with it. I’m using state_machine to skip If-else statements for the animations.

  1. The guard chases the prisoner if the prisoner is in sight.
  2. The guard attacks the prisoner if the prisoner is in range.

Patrolling state below:

extends State
class_name Patrol
 
@onready var prison_guard = $"../.."
@onready var navigation_agent = $"../../NavigationAgent3D"
@onready var prisoner: MeshInstance3D = $Prisoner
@onready var ray_cast_3d: RayCast3D = $Prisoner/RayCast3D
 
var current_marker: Marker3D = null
var markerIndex = null
 
@onready var patrol_markers: Array[Marker3D] = prison_guard.patrol_markers

func physics_update(_delta: float) -> void:
	var nextMarker = select_next_marker(current_marker)
	move_toward_marker(nextMarker, _delta)

func select_next_marker(next_marker):
	if markerIndex == null:
		markerIndex = 0
		current_marker = patrol_markers[markerIndex]
		
	if navigation_agent.is_target_reached() or not navigation_agent.is_target_reachable():
		markerIndex += 1
		if markerIndex >= len(patrol_markers):
			markerIndex = 0
	return patrol_markers[markerIndex]

 
func move_toward_marker(marker, delta):
	var direction := Vector3()
	navigation_agent.target_position = marker.global_position
	direction = navigation_agent.get_next_path_position() - prison_guard.global_position
	prison_guard.look_at(marker.global_position + direction)
	prison_guard.rotate_y(deg_to_rad(180))
	direction = direction.normalized()
	var speed = prison_guard.walking_speed
	prison_guard.velocity = prison_guard.velocity.lerp(direction * speed, 1.0 * delta)
	prison_guard.move_and_slide()


func enter(_msg :={}) -> void:
	if state_machine.animation_player:
		state_machine.animation_player.play("Walk")
	
func exit() -> void:
	if state_machine.animation_player:
		state_machine.animation_player.stop()

My prison_Guard code below:

extends CharacterBody3D
 
@export var walking_speed = 5.0
@export var chasing_speed = 10.0
@export var attack_speed = 10.0
@export var vision_length = 100
 
@export var patrol_markers: Array[Marker3D] = []
 
func _physics_process(delta: float) -> void:
	pass