I’m currently making an evil ai robot for a game. The robot needs to follow you where ever you go.
The moving script uses pathfindingservice to prevent the robot from getting stuck.
Problem is that the robot first completes the path to the original location of the path in stead of taking the fast way to the destination directly.
Here’s what I mean; https://gyazo.com/f5852e83949f5f1ce9e6f89eb670dd7e
If you don’t understand it, I made this; https://gyazo.com/11b37021e89d515328df809f36e5c7ee
This is my script:
local PathService = game:GetService("PathfindingService")
while wait() do
local SmoothPath = PathService:ComputeSmoothPathAsync(workspace.Robot.HumanoidRootPart.Position,workspace.End.Position,512)
local path = SmoothPath:GetPointCoordinates()
workspace.Points:ClearAllChildren()
for i=1,#path do
local pos = path[i]
local p = Instance.new("Part",workspace.Points)
p.Anchored = true
p.CanCollide = false
p.Size = Vector3.new(1,1,1)
p.Position = pos
p.Color = Color3.fromRGB(255,0,0)
workspace.Robot.Humanoid:MoveTo(p.Position)
workspace.Robot.Humanoid.MoveToFinished:Wait()
end
end
The script pretty much calculates the route, and then moves to the position. By using the for loop to move the AI, it can’t do anything else (including calculating a new route) until the AI finishes the for loop (finishes the path). To prevent this, i would recommend checking if the player has moved each time the for loop runs, and recalculate the route if it has.
Try using ‘break’ to exit the for loop if the player has moved.
local PathService = game:GetService("PathfindingService")
while wait() do
local SmoothPath = PathService:ComputeSmoothPathAsync(workspace.Robot.HumanoidRootPart.Position,workspace.End.Position,512)
local path = SmoothPath:GetPointCoordinates()
workspace.Points:ClearAllChildren()
for i=1,#path do
if player has moved then
break
end
local pos = path[i]
local p = Instance.new("Part",workspace.Points)
p.Anchored = true
p.CanCollide = false
p.Size = Vector3.new(1,1,1)
p.Position = pos
p.Color = Color3.fromRGB(255,0,0)
workspace.Robot.Humanoid:MoveTo(p.Position)
workspace.Robot.Humanoid.MoveToFinished:Wait()
end
end
Remember to check if the player has moved before the ‘if’ statement but still inside the for loop.