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

Loop to move character only runs once?

Asked by 7 years ago
Edited 7 years ago

Seriously... What on EARTH is going on here.... As you can tell by the output, the loop is supposed to run 104 times, but it only runs once! This is probably the 4th time that I restarted this script, and by now I am just confused. I get this same result every time.

Here is the output.

local model = script.Parent
local humanoid = model:WaitForChild("Humanoid")
local torso = model.Torso
local hrp = model.HumanoidRootPart
local cspawn = model.CSpawn
local current_target = model.CurrentTarget
local animations = model.Animations
local crystalPart = workspace.Crystal.FinalMT
local pfs = game:GetService("PathfindingService")

function getNearestEnemy()
    for _, v in pairs(workspace:GetChildren()) do
        if v.Parent ~= model.Parent then
            if v:FindFirstChild("Humanoid") then
                if v.Parent == workspace.Troops then
                    local dis = (v.Torso.CFrame.p - torso.CFrame.p).magnitude
                    if dis < 10 then
                        return v
                    end
                end
            end
        end
        return nil
    end
end

function visualize(path) -- Put this here to make sure the path is even getting made..
    local points = path:GetPointCoordinates()

    for _, point in ipairs(points) do
        local p = Instance.new("Part", workspace)
        p.Size = Vector3.new(1,1,1)
        p.Anchored = true
        p.CanCollide = false
        p.CFrame = CFrame.new(point)
    end
end

local moveToCrystal = coroutine.create(function()
    print'moving to crystal'
    local path = pfs:ComputeRawPathAsync(torso.Position, crystalPart.Position, 500)
    local points = path:GetPointCoordinates()

    visualize(path)
    for _, point in pairs(points) do
        humanoid:MoveTo(point)
        local distance
        print'moved to point'
        print(#points)
        repeat
            distance = (torso.CFrame.p - crystalPart.CFrame.p).magnitude
            wait()
        until distance < 5
    end
end)

local chaseTroop = coroutine.create(function(char)
    local path = pfs:ComputeRawPathAsync(torso.Position, char.Torso.Position, 500)
    local points = path:GetPointCoordinates()

    visualize(path)
    for _, point in ipairs(points) do
        humanoid:MoveTo(point)
        local distance

        repeat
            distance = (torso.CFrame.p - char.Torso.CFrame.p).magnitude
            wait()
        until distance < 5
    end
end)

while wait(0.1) do
    local nearest = getNearestEnemy()
    print'refresh'
    if nearest then
            coroutine.yield(moveToCrystal)
            coroutine.resume(chaseTroop, nearest)
    else
            coroutine.yield(chaseTroop)
            coroutine.resume(moveToCrystal)
    end
end

Answer this question