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

My script that judges distance of blocks in a group and the closest one is printed is not working?

Asked by 7 years ago
Edited 7 years ago

Im trying to make something judging by the distance of the parts, here is what I have so far,

local lastdist, lastv, closestdist
group = script.Parent

for i,v in pairs(group:GetChildren()) do
    lastdist = distance
    distance = (game.Players.LocalPlayer.Character.Torso.Position - v.Position).magnitude
    if lastv ~= nil then
        lastdist = (game.Players.LocalPlayer.Character.Torso.Position - lastv.Position).magnitude
    end
    if lastdist ~= nil and distance < lastdist then
        closestdist = distance
    end
    lastv = v
end
print(closestdist)

There is no error but it isnt printing it. Please help!

PS: it's in a local script

1 answer

Log in to vote
1
Answered by 7 years ago

You have no defined distance so lastdist = distance will be nil each time. Since you check that lastdist ~= nil closestdist is never assigned a value meaning it will be nil each time.

I feel that you are over complicating this. We only need to store the players position, the closest part part and distance ( so we do not need to calculate it each time) then loop and check each parts position.

Example:-

-- you should make a function if you use the code more than once
local function findClosestPart(group, position)
    local closestPart, closestPartMagnitude

    local tmpMagnitude -- to store our calculation 
    for i, v in pairs(group:GetChildren()) do
        if closestPart then -- we have a part
            tmpMagnitude = (position - v.Position).magnitude

            -- check the next part
            if tmpMagnitude < closestPartMagnitude then
                closestPart = v
                closestPartMagnitude = tmpMagnitude 
            end
        else
            -- our first part
            closestPart = v
            closestPartMagnitude = (position - v.Position).magnitude
        end
    end
    return closestPart, closestPartMagnitude
end

print(findClosestPart(script.Parent, game.Players.LocalPlayer.Character.Torso.Position))

I hope this helps.

0
thanks! Benified4Life 2 — 7y
Ad

Answer this question