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

Distance in 3 Dimensional space?

Asked by 9 years ago

I need to write a function that returns the distance between two models. Any help?

1 answer

Log in to vote
3
Answered by 9 years ago
local function findDistance(position1, position2) --Takes two Vector3 arguments
    local X1 = position1.X; local X2 = position2.X;
    local Y1 = position1.Y; local Y2 = position2.Y;
    local Z1 = position1.Z; local Z2 = position2.Z;

    return math.sqrt((X2-X1)^2+(Y2-Y1)^2+(Z2-Z1)^2)
end

Or you could have a function that works with both Vector2 and Vector3

local function findDistance(position1, position2)
    local distance = 0;
    if position1:IsA("Vector3") and position2:IsA("Vector3") then
        local X1 = position1.X; local X2 = position2.X;
        local Y1 = position1.Y; local Y2 = position2.Y;
        local Z1 = position1.Z; local Z2 = position2.Z;
        distance = math.sqrt((X2-X1)^2+(Y2-Y1)^2+(Z2-Z1)^2);
    elseif position1:IsA("Vector2") and position2:IsA("Vector2") then
        local X1 = position1.X; local X2 = position2.X;
        local Y1 = position1.Y; local Y2 = position2.Y;
        distance = math.sqrt((X2-X1)^2+(Y2-Y1)^2)
    end
    return distance;
end
0
Thanks, this is exactly what I needed! thethemast667 10 — 9y
0
For a much simpler to implement example: (position1 - position2).magnitude adark 5487 — 9y
0
It seems that most of the basic math is already built into Roblox. This function can be used as a base for other things though. DewnOracle 115 — 9y
0
Omg, excellent answer! I'll be sure to use this in my scripts. Thanks! yumtaste 476 — 9y
View all comments (4 more)
0
Does this work with any Vector3 vlaue? thethemast667 10 — 9y
0
Yes, yes it does. DewnOracle 115 — 9y
0
It only works with Vector3s is the only issue. .magnitude works for Vector2s as well. adark 5487 — 9y
0
It wouldn't be to hard to type test the arguments first then conditionally calculate. DewnOracle 115 — 9y
Ad

Answer this question