How do i make my enemies move towards my player? (SOLVED)

I am attempting to implement a system to allow enemy objects to move to the player position, however when the game is loaded, it instead moves towards the right wall and returns this error

ERROR:SCRIPT: main/enemies/skeleton/skeleton.script:24: bad argument #1 to '__add' (vector3 expected, got nil)
stack traceback:
  [C]:-1: in function __add
  main/enemies/skeleton/skeleton.script:24: in function <main/enemies/skeleton/skeleton.script:14>

Here is my code for the enemy:

local speed=125
local enemy_health=5
local damage=5
local score=20

function init(self)
	msg.post(".", "acquire_input_focus") -- tells object to listen for inputs
	self.dir = vmath.vector3(1, 0, 0)
	self.current_anim=nil -- stores current animation
	self.speed=speed -- stores speed
	--posistion = go.get_position() -- get position of object
end

function update(self, dt)
	if vmath.length_sqr(self.dir) > 1 then
		self.dir = vmath.normalize(self.dir) -- normalises direction vector - allows for diagonal movement
	end
	local p = go.get_position() -- fetches the new position
	go.set_position(p + self.dir * speed * dt) -- sets new position

	local anim=hash("skeleton_idle")

	pos = go.get_position() -- sets pos for comparison
	pos = position + self.dir * speed * dt 
	player_pos = go.get_position("/player") -- gets player's pos
	distance = vmath.length(pos - player_pos) -- Compares the player and enemy position

	print(player_pos)
	
	if self.dir.x ~= 0 then -- check if vectors are not 0
		pos = pos + self.dir * dt
		go.set_position(pos)
		anim=hash("skeleton_run")
	elseif self.dir.y ~= 0 then
		pos = pos + self.dir * dt
		go.set_position(pos)
		anim=hash("skeleton_run")
	end

	if anim ~= self.current_anim then -- checks if animation is the same
		msg.post("#sprite", "play_animation", { id = anim }) -- plays new animation
		self.current_anim=anim -- changes id to new animation id
	end

	self.dir = vmath.vector3() -- resets direction vector

	if enemy_health < 0 then
		msg.post("/UI#main", "add_score", {amount=score})
		go.delete()
	end

	if vmath.length(pos - player_pos) < distance then
		self.speed = speed * 0
	end
end

function on_message(self, message_id, message, sender)
	if message_id==hash("remove_health") then
		enemy_health=enemy_health-message.amount
	end

	if message_id==hash("contact_point_response") then -- detects contact
		go.set_position(pos+message.normal*message.distance) -- corrects position
	end
end

You reset self.dir but you never set a new value for it.

I would expect a line like:

self.dir = go.get_position("player_path") - go.get_position()

somewhere in your update() function

EDIT: I made a simple chasing game, you can find code here: https://github.com/robotigerhub/desktop-game

1 Like

I changed the line, it now works wonders, thank you

2 Likes