How do I make an enemy movement and AI?

I’m having trouble giving my enemy in my top-down game. I can’t seem to get the movement right at all.
Here is my code:


function update(self, dt)
	local player_pos = go.get_position("/player/go")
	local pos = go.get_position()
	local enemy_pos = go.get_position()

	print(player_pos)

	if self.speed.x == 0 then
		pos = pos + self.speed * dt
		go.set_position(pos)
		if self.cur_anim ~= "enemy_idle" then
			msg.post("#sprite", "play_animation", {id=hash("enemy_run")})
			self.cur_anim = "enemy_run"
		end
	end

	if self.speed.y == 0 then
		pos = pos + self.speed * dt
		go.set_position(pos - player_pos)
		if self.cur_anim ~= "enemy_idle" then
			msg.post("#sprite", "play_animation", {id=hash("enemy_run")})
			self.cur_anim = "enemy_run"
		end
	end
	
	if enemy_pos == player_pos then
		self.speed = self.speed * 0
	end
end

You didn’t tell us of the actual results vs what you want. Does the code you shared crash? Do you have any errors in the console? What kind of behavior do you want for the enemy? Moving in a straight line towards the player?

Unless you’re using integer math (you’re not by the looks of it), you shouldn’t use exact comparisons between floating point numbers.

Instead, I recommend using a proximity check:

if vmath.length(enemy_pos - player_pos) < distance then
...
1 Like