Creating an enemy AI that chases player and avoids obstacles

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By IsaiahDicristoforo

I am working on a script where a zombie (Kinematic body 2d) chases a player in a top down shooter game. Currently, this script works fine, unless the zombie gets blocked by some obstacle in the form of a static 2d node. How can I code my enemy AI so that the enemy continues to chase the player while navigating around certain obstacles in my world?

const MOVE_SPEED = 200
onready var raycast = $RayCast2D
var player = null
func _ready():
func _physics_process(delta):
	if player == null:
	var vec_to_player = player.global_position - global_position
	vec_to_player = vec_to_player.normalized()
	global_rotation = atan2(vec_to_player.y, vec_to_player.x)
	move_and_collide(vec_to_player * MOVE_SPEED * delta)
	if raycast.is_colliding():
		var coll = raycast.get_collider()
		if == "Player":
:bust_in_silhouette: Reply From: p7f

Instead of calculating the direction and just moving towards the player, you should use Navigation2D. Is a bit long to explain here, but this links has the information you need.

Tutorial by GDQuest
Navigation2D docs

If you are not using TileMaps, you can still follow the video but creating a NavigationPolygonInstance yourself. Add the NavigationPolygonInstance as a child of the Navigation2D node in your scene.