Hello, I’ve been trying to learn how to use the PathfindingService for testing in my game, but I keep failing to do so. The AI messes up entirely on it’s path.
I’ve tried looking around the DevForum and other sites to find a solution but none of them were answering my question on how to get the nearest character targeted.
https://gyazo.com/07bc56ac44481d0f288ec73743a05497
Here’s an image, of how it acts.
The AI manages to only Follow you, but I know why it’s most likely breaking is because I’m not waiting for it to stop after reaching the destination. But the problem is, it’ll just go after the last position I was in then try to go after the players.
I want it to achieve by using AI Pathfinding to get any near players and target those who are near, and will not get stuck or go after the remaining position.
Here is my coding so far.
local RunService = game:GetService("RunService")
local Pathfinding = game:GetService('PathfindingService')
local TweenService = game:GetService("TweenService")
local Path = Pathfinding:CreatePath()
local Friendly = false
local Damage = 1
local Debounce = false
local Character = script.Parent
local Humanoid = Character:WaitForChild("Humanoid")
function GetNearestCharacters()
local ClosestCharacter, Distances = nil,100
for _, Player in pairs(game.Workspace:GetChildren()) do
if Player:FindFirstChild("Humanoid") and Player ~= Character then
local Distance = (Character.PrimaryPart.Position - Player.PrimaryPart.Position).Magnitude
if Distance < Distances then
ClosestCharacter = Player
Distances = Distance
end
end
end
return ClosestCharacter, Distances
end
while wait() do
local Player, Distance = GetNearestCharacters()
if Player then
Path:ComputeAsync(Character.PrimaryPart.Position, Player.PrimaryPart.Position)
if Path.Status == Enum.PathStatus.Success then
local Waypoints = Path:GetWaypoints()
for _,Waypoint in pairs(Waypoints) do
if Waypoint.Action == Enum.PathWaypointAction.Jump then
Humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
end
Humanoid:MoveTo(Waypoint.Position)
end
elseif Path.Status == Enum.PathStatus.NoPath then
warn("PathStatus was a failure, retrying...")
end
end
end
I’d like atleast an understanding or a correction in my programming, I’m new to pathfindingservice so this might be the most annoying to work with lol.