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

Problem with this script for moving around an enemy?

Asked by
sheepposu 561 Moderation Voter
4 years ago

I was making an enemy, and all was going well until I found this bug. I don't know how exactly it works, but when I move a certain way for some reason it throws off the script and the enemy begins to move straight the direction about 90 degrees from the way I'm facing. I've been looking at it for quite a bit and I cant find what's going wrong. Thx in advance for any help.

local startingPos = script.Parent.HumanoidRootPart.Position


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

while true do
    wait()
    local target = findNearestTorso(script.Parent.HumanoidRootPart.Position)
    if target ~= nil then
        script.Parent.Humanoid:MoveTo(target.Position, target)
    else
        script.Parent.Humanoid:MoveTo(startingPos)
    end
end

Answer this question