Is it worth using some kind of true/false variable to keep track of whether its reached the target or not?
Yes, exactly!
Typically should logic is like
function init(self)
self.dir = vmath.vector3()
self.speed = reg_speed
-- Lets store the flag for target following:
self.is_executing_route = false
end
--First let's make some additional functions for more clarity:
local function move_closer_to_player(self, dt)
-- Implement logic for moving closer to the player. Remember to move enemy just a little bit closer to player, not to player position! Also route execution flag should be set to false.
end
local function continue_route(self, dt)
-- Implement logic for continuing the current route. Remember to move enemy just a little bit closer to target position, not immediately to the target pos! Also check if you have reached the target point here (or you are close enough).
end
local function get_new_target(self, dt)
-- Implement logic for getting a new target. Just getting new target, you can also call continue_route() to move a little bit in the same frame. Dont forget to set the is_executing_route flag to true.
end
function update(self, dt)
local player_pos = go.get_position("Player")
local enemy_pos = go.get_position()
local distance = vmath.length(player_pos - enemy_pos)
local is_player_close = distance < 100
if is_player_close then
move_closer_to_player(dt)
else
if self.is_executing_route then
continue_route(dt)
else
get_new_target(dt)
end
end
end
I have not tested the code above, I just writen it directly here, so there may be some mistakes, but I hope it gives you an idea what can be done.
Also as @Alex_8BitSkull mentioned, try using higher values for target coordinates. Maybe start with printing player coordinates when traversing map to get a grasp of range that interests you?