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

Can I make this AI detect and follow players faster?

Asked by
Uluomis 32
4 years ago

So I made a script that creates an AI with a pathfinding ability that tries to kill you. It works but the only problem is that when there are multiple people it slows down and its movement becomes stuttery. How could I fix this?

function findNearestTorso(pos)
    local list = game.Workspace:children()
    local torso = nil
    local dist = 200
    local temp = nil
    local human = nil
    local temp2 = nil
    for x = 1, #list do
        temp2 = list[x]
        if (temp2.className == "Model") and (temp2 ~= script.Parent) then
            temp = temp2:findFirstChild("HumanoidRootPart")
            human = temp2:findFirstChild("Humanoid")
            if (temp ~= nil) and (human ~= nil) and (human.Health > 0) then
                if (temp.Position - pos).magnitude < dist then
                    torso = temp
                    dist = (temp.Position - pos).magnitude
                end
            end
        end
    end
    if torso == nil then
    else
    return torso.Position
    end
end

while true do
    local target = findNearestTorso(script.Parent.Torso.Position)
    if target ~= nil then
        local pathfindingService = game:GetService("PathfindingService")
        local humanoid = script.Parent.Enemy

        local body = script.Parent.Torso

        local path = pathfindingService:CreatePath()
        path:ComputeAsync(body.Position, target)

        local waypoints = path:GetWaypoints()

    for k, waypoint in pairs(waypoints) do
    humanoid:MoveTo(waypoint.Position)

    if waypoint.Action == Enum.PathWaypointAction.Jump then
        humanoid:ChangeState(Enum.HumanoidStateType.Jumping)
    end
    humanoid.MoveToFinished:Wait()
    end
    end
    wait()
end
0
This doesn't have to do with your script. Rather, it has to do with who handles the physics of the Humanoid. I'd suggest reading up on Network Ownership. (https://developer.roblox.com/en-us/articles/Network-Ownership) y3_th 176 — 4y
1
You don't need to be recalculating waypoints every step. Only do it every second or so, and just save them in between. More in this article thingy: https://developer.roblox.com/en-us/articles/Pathfinding fredfishy 833 — 4y
0
Where would I make the script wait? Uluomis 32 — 4y

1 answer

Log in to vote
-1
Answered by 4 years ago

You can make it detect through character position in workspace but your code is already fastest. Sorry

Ad

Answer this question