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

Character Lock-On script not working when finding nearest target?

Asked by 5 years ago

It will work with a any seperate NPC, But when I try to get it to work while finding the closest NPC in range then it wont work.

local localPlayer = game:GetService("Players").LocalPlayer
local Character = localPlayer.Character
local localRootPart = Character:FindFirstChild("HumanoidRootPart")

local Position1 = localRootPart
local Position2 = nil

function findTarget()
    local Distance = 100
    local Target = nil
    for i, v in pairs(workspace:GetChildren()) do
        local Human = v:FindFirstChild("Humanoid")
        local rootPart = v:FindFirstChild("HumanoidRootPart")
        if Human and rootPart and v ~= Character then
            if Human.Health > 0 then
                if (localRootPart.Position - rootPart.Position).magnitude < Distance then
                    Distance = (localRootPart.Position - rootPart.Position).magnitude
                    Target = rootPart
                end
            end
        end
    end
    return Target
end

while wait(1) do
    local rootPart = findTarget()
    if rootPart and Position2 == nil then
        Position2 = rootPart
    end
end

function onRenderStepped()
    bodyGyro.CFrame = CFrame.new(Position1.Position, Position2.Position)
end
0
Try making Position1 and Position2 a global variable? I'm not sure Warfaresh0t 414 — 5y

Answer this question