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.
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
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.