This site is currently in read-only mode during migration to a new platform.
You cannot post questions, answers or comments, as they would be lost during the migration otherwise.
0 votes

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():
    add_to_group("zombies")

func _physics_process(delta):
    if player == null:
        return
    get_node("AnimatedSprite").play()
    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 coll.name == "Player":
            coll.kill()
in Engine by (15 points)

1 Answer

+2 votes
Best answer

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.

by (3,505 points)
selected by
Welcome to Godot Engine Q&A, where you can ask questions and receive answers from other members of the community.

Please make sure to read Frequently asked questions and How to use this Q&A? before posting your first questions.
Social login is currently unavailable. If you've previously logged in with a Facebook or GitHub account, use the I forgot my password link in the login box to set a password for your account. If you still can't access your account, send an email to [email protected] with your username.