- What do you want to achieve? Keep it simple and clear!
- I want to have my NPC’s nearest player pathfinding work well without stopping, and with the ability to navigate around obstacles like pathfinding is meant for.
- What is the issue? Include screenshots / videos if possible!
- My issue is that without using Humanoid.MoveToFinished:Wait(), the NPC runs into walls even though the path shows that it should be moving around them, but when I use it, my NPC can get around obstacles but “stutters” or is just way too slow.
Video of the NPC without Humanoid.MoveToFinished:Wait()
Video of the NPC with Humanoid.MoveToFinished:Wait()
- What solutions have you tried so far? Did you look for solutions on the Creator Hub?
- I have looked through several Dev Forum posts, and even the ones with solutions marked didn’t seem to work for me when I tried the solutions. An example of one of these solutions is constantly checking whether the NPC is within a certain range and if it is not fast enough then it will skip to the next waypoint. (Didn’t work and performed exactly the same as with using MoveToFinished)
My script, without using Humanoid.MoveToFinished:Wait():
local PathfindingService = game:GetService("PathfindingService")
local rig = script.Parent
wait(1)
local function GetClosestTarget()
local target = nil
local distances = {}
local playersList = game.Players:GetChildren()
for i,v in pairs(playersList) do
local dist = v:DistanceFromCharacter(rig.PrimaryPart.Position)
if dist <= 50 then
table.insert(distances, {dist, v})
end
end
table.sort(distances, function(a,b)
return a[1] < b[1]
end)
if #distances > 0 then
target = distances[1][2]
end
return target
end
local attacking = false
local function Attack(target)
local anim = rig.Humanoid.Animator:LoadAnimation(rig.attackAnim)
local damage = 20
if not attacking then
attacking = true
anim:Play()
if target then target.Character.Humanoid.Health -= damage end
wait(1.25)
attacking = false
end
end
while wait(.1) do
local target = GetClosestTarget()
if target then
local path = PathfindingService:CreatePath({
AgentRadius = 4,
})
path:ComputeAsync(rig.PrimaryPart.Position, target.Character.PrimaryPart.Position)
local waypoints = path:GetWaypoints()
for i,waypoint in pairs(waypoints) do
local part = Instance.new("Part", workspace)
part.Position = waypoint.Position
part.Size = Vector3.new(.5,.5,.5)
part.Color = Color3.new(1, 1, 1)
part.Shape = "Ball"
part.Anchored = true
part.CanCollide = false
game.Debris:AddItem(part, .5)
rig.Humanoid:MoveTo(waypoint.Position)
local magnitude = target:DistanceFromCharacter(rig.PrimaryPart.Position)
if magnitude < 3 then
rig.Humanoid:MoveTo(rig.PrimaryPart.Position)
Attack(target)
end
end
else
rig.Humanoid:MoveTo(rig.PrimaryPart.Position)
end
end