Topic was automatically imported from the old Question2Answer platform.
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.
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":
idle()
else if == "chasing":
chasing()
else:
patrol()
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()
move_to(player_position)
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.