Way for AI to follow player when they are within a certain distance

Hi,

I am trying to make a simple AI that will begin to chase the player when the player gets within a certain distance of the player. What would be the easiest way to do this?

I already have an AI path of where they will walk, but can’t figure out how to implement it. I don’t need to worry out the AI avoiding walls and things yet.

Thanks

This allows you to get the distance between two positions:

vmath.length(position1 - position2)

3 Likes

Hi,
Used the API reference you linked and another tutorial for an AI following an input and tried to use the two of them for this. But when I copied the code from Follow input and changed some of the variables to suit my code, the “duration” variable outputted an error.

Not really sure what I have done wrong, would appreciate the help. Thanks

function update(self, dt)
	--Initialises the local variable position
	local position = go.get_position()

	--The distance travelled will add to the initial distance
	go.set_position(position + self.speed * dt)

	if vmath.length((go.get_position(player)) - (go.get_position())) >= 50 then
		--Stops the guard from leaving the boundary and turns them around
		--Only acting in the y-axis
		print("not chase")
		if (go.get_position().y <= 0) then
		self.speed = vmath.vector3(0, 100, 0)
		end 

		if (go.get_position().y >= 500) then
			self.speed = vmath.vector3(0, -100, 0)
		end

	elseif vmath.length((go.get_position(player)) - (go.get_position())) <= 50 then
		print("chase")
		local target_position = go.get_position(player)
		local distance = vmath.length(target_position - go.get_position())
		local duration = (distance) / (self.speed)
		go.animate(".", "position", go.PLAYBACK_ONCE_FORWARD, target_position, go.EASING_LINEAR, duration, 0)
	end
end

The console never prints the “not chase” line, but the AI will still follow the AI path set in that same if statement, so the condition for it must be met

EDIT: The parentheses are messy but correct. :man_facepalming: The issue is most likely what was posted after this!

I think you’ve got your parentheses a bit wrong here. It looks like you end the vmath.length function immediately after getting the player position.

	if vmath.length(go.get_position(player) - go.get_position()) >= 50 then

This should work. Or at least, get you to the next error :slight_smile:

Your error says it all:

  • “_div” is the “/” operator
  • You’re trying to divide something by using a vector (e.g. “v / vmath.vector3(a,b,c)”) which won’t work
  • Looking through your code, it’s your local duration = (distance) / (self.speed) that is at fault
3 Likes

Oh yeah! At first I thought “but speed is a scalar?” except in this case it isn’t. It would be called a velocity (which is speed + direction, in this case 100 pixels per second upwards).

You could convert this velocity to an actual speed by using vmath.length on it.

3 Likes