0 votes

Hi, how can i make an enemy that when the player enters in the 2D area of the enemy the enemy chases him until the player exits the area.

in Engine by (55 points)

Hi, can you give more information about your issue. What are the points that block you?

I don't know how to make the enemy move when the player comes into contact with the Area. So far I have only created an enemy that moves and changes direction when it encounters an obstacle.

1 Answer

+1 vote

I recomend you to look to state machine pattern ( https://www.youtube.com/watch?v=4bdiyOGHLtM) and watch other tutorials about basic platformer.
It's a bit hard to tell you what exactly do, because there is so many way.

But here one, very simple for very basic IA.

The idea is to have differents behaviour for each states ; idle, patrol, chasing

When the enemy will detect the player, you should change state, for example "chassing". Then in the process function call the fuction corresponding to a state.

Here's some pseudo code to get the logic. You should adapt it to suit your code mouvement logic

extends Node

class_name Enemy

var state = "Idle"  
var speed = 5

func _process(delta):
   if state == "idle":
   else if == "chasing":

func idle():
    # Idle stuff

func patrol():
    # Patrol stuff

func chasing()
     # You should stock or create a function to acces to the position player
       var player_position = get_player_position()

If you don't understand how get the direction works, please read https://docs.godotengine.org/en/3.2/tutorials/math/vector_math.html

func move_to( pos : Vector2):

var direction = pos - self.position
var normalized = direction.normalized()

self.position += normalized * speed * delta

func _on_Body_entered(body):
    # You should check somewhere is the body, is the player
    state = chasing

func _on_Body_exited(body):
    # You should check somewhere is the body, is the player
    state = patrol

And I repeat, but this is some basic code, note perfect, can be improve, but working for simple purpose and when you're begining IA.

by (288 points)
edited by

Thanks! I'll try it.

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 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 webmaster@godotengine.org with your username.