How to code 8-way movement for my enemy?

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

I coded 8-way movement for player, but i dont know how to make enemies move

:bust_in_silhouette: Reply From: Unknowledge

There are several ways to make the enemy AI move, but it all depends on your project. You might want that the AI is able to avoid objects on its way, for that you can use Navigation2D or AStar node, or you might want a more simple code, where the AI simply moves towards the player. For that you can make a code like that (please notice that you would have to adapt it to your project, the following code is just to give you a idea)

The code:

var positionx = 0
var positiony = 0
var speed = 100
var movedir = Vector2()

var player = get_node("root/Player")

if(player.global_position.x < self.global_position.x):
	positionx = -1
if(player.global_position.x > self.global_position.x):
	positionx = 1
if(player.global_position.y < self.global_position.y):
	positiony = -1
if(player.global_position.y > self.global_position.y):
	positiony = 1

movedir = Vector2(positionx, positiony)
var motion = movedir * speed
move_and_slide(motion, Vector2())

If you have any question about the code or other ways to make the enemy AI move, don’t be afraid to ask me.