Scripting Helpers is winding down operations and is now read-only. More info→
Ad
Log in to vote
0

How do I fix my chasing, pathfinding AI?

Asked by 4 years ago
Edited 4 years ago

So I am trying to make a chasing, pathfinding "Peter Griffin" AI. It has a Humanoid, a script called "Follow" and a MeshPart called "Petermodel". It has a Part called "Head", and a Part called "Torso" with two welds in it, welded to the "Head" and the "Petermodel".

Here is the script, ignore the comments in it:

local root = script.Parent.HumanoidRootPart
local hum = script.Parent.Humanoid

function findTarget() -- this is the function that would locate the nearest human; we will constantly be spamming this.
    local dist = 200
    local target = nil
    for i, v in pairs(workspace:GetChildren()) do
        local human = v:FindFirstChild("Humanoid")
        local head = v:FindFirstChild("Head")

        if human and head and v.Name ~= "Peter Griffin" then -- u could remove this if u want ur Peter to attack other Peters
            local mag = (head.Position - root.position).Magnitude

            if mag < dist and human.Health > 0 then
                dist = mag
                target = head
            end
        end
    end

    return target
end

while wait(.1) do
    local head = findTarget()

    if head then
        local ray = Ray.new(root.Position, (head.Position - root.Position).Unit * 200)

        local hit, pos = workspace:FindPartOnRay(ray, script.Parent, true, false) -- ignore list
        if hit:IsDescendantOf(head.Parent) then
            hum:MoveTo(head.Position)

        else
            hum:MoveTo(head.Position) -- less choppy movement; a lot of the following is also for such
            wait(.05)
            path = game:GetService("PathfindingService"):FindPathAsync(root.Position, head.Position) -- get the Pathfinding service
            points = path:GetWaypoints()

            if path.Status == Enum.PathStatus.Success then
                for i, v in pairs(points) do
                    hum:MoveTo(v.Position)
                    hum.MoveToFinished:Wait(2) -- 2 as a safety precaution
                    if v.Action == Enum.PathWaypointAction.Jump then -- if the Peter is required to jump then we make the Peter jump
                        hum.Jump = true
                    end
                    if (points[#points].Position - head.Position).Magnitude > 15 then
                        break
                    end
                end
            else
                hum:MoveTo(head.Position)
            end
        end
    end
end

He does not move at all. This is my first question so it may be a bit bad looking, but help would be appreciated!

0
what is the problem? Does he move in an unwanted way or not move at all? Dfzoz 489 — 4y

Answer this question