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

Find Distance Script?

Asked by 8 years ago

So, I'm working on a script that will find the distance between an NPC and (currently) 2 blocks, and move the NPC to which ever block is closest. I'm making the script using Region3 so that it senses all blocks in the area, that way I can add more or less blocks to the area without having to re-write the script. Here's my script:

local base = game.Workspace.Base

local point1 = Vector3.new(0,0,0)
local point2 = Vector3.new(100,100,100)
local Region = Region3.new(point1,point2)

for _,Part in pairs(game.Workspace:FindPartsInRegion3(Region,nil,100)) do
    if Part.Name == "building" then

        end
    end

I'm super stuck at this point. I've tried for hours, but I can't figure out how to make the script get each blocks position individually, instead of combining all the positions into one variable "Part".

Any help on what to do from this point?

1 answer

Log in to vote
1
Answered by 8 years ago

To get the distance between parts, use the following method:

local base = game.Workspace.Base

local point1 = Vector3.new(0,0,0)
local point2 = Vector3.new(100,100,100)
local Region = Region3.new(point1,point2)

local parts = game.Workspace:FindPartsInRegion3(Region,nil,100)
---------------------------------------------------------------------------------------- This is the part that gets the magnitude.
local pos = {} -- table for parts
local vals = {} -- table for position values

function getMagnitude(part1,part2)
    local mag = (part1.Position - part2.Position).magnitude
    return mag
end

for i = 1,#parts do -- so you can get current number
    if parts[i].Name == "building" then
        table.insert(pos,parts[i])
        table.insert(vals,getMagnitude(base,parts[i]))
        end
end
------------------------------------------------------------------------------------------
wait()

local lowest
local pTable = {}

function getPart(m)
    for i = 1,#parts do
        if getMagnitude(base,parts[i]) == m then
            table.insert(pTable,parts[i])
        end
    end
end

for i = 1,#vals do
    if lowest ~= nil then
        if lowest <= vals[i] then
            lowest = vals[i]
        end
    else
        lowest = vals[i]
    end
end

wait()
getPart(lowest)
wait()

if #pTable > 1 then
    local str
    for i = 1,#pTable do
        str = str.. ", " ..pTable[i].Name
    end
    wait()
    print(str.. " are the closest with a tied magnitude.)
else
    print(pTable[1].Name.. " is the closest.")
end


This script also gets the closest one.

This should work, and hopefully you can fix any bugs (if there are any).

0
This is very unnecessarily complicated. You need only .magnitude. Marios2 360 — 8y
0
Yes. Lol, just so he can use it expanded without changing much. TheDeadlyPanther 2460 — 8y
Ad

Answer this question