Help with 2D platformer enemy

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

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.

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

UnRealCloud 1 | 2020-07-28 20:06

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.

Simon | 2020-07-28 20:16

:bust_in_silhouette: Reply From: UnRealCloud 1

I recomend you to look to state machine pattern ( 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 Vector math — Godot Engine (3.2) documentation in English

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.

Thanks! I’ll try it.

Simon | 2020-07-30 10:18