How to find the distance of a part to another part with on only one axis (the first part's RightVector)

Hello everyone, I want to know how to calculate the distance of a part to another part but only on the RightVector. For example, if the second part was to the left of the first part, it would be like -2.5 and if it was to the right it would be 2.5.

Any help would be appreciated!

You can utilize raycasting to get the distance between two parts. Here’s an example from the Roblox Documentation.

local rayOrigin = workspace.TestOrigin.Position
local rayDestination = workspace.TestDestination.Position

local rayDirection = rayDestination - rayOrigin

local raycastResult = workspace:Raycast(rayOrigin, rayDirection)

If you are only using 2 numbers, some simple math will do.

If for example the 2 numbers were -4 and 2, then we could figure out the distance with this:

local number1 = -4
local number2 = 2
local result = math.abs(number1 - number2)

print(result) -- 6
1 Like
—this works for any orientation
local function getXDistanceRelativeToPart(part1, part2) —if you dont care about the y and z direction
    local YZDistance = (part2.Position-Part1.Position).Magnitude
    return part1.CFrame.RightVector:Dot(YZDistance.Unit) * YZDistance —returns the distance between part1’s origin and part2’s position projected onto part1’s right vector
end
1 Like

im scared this will not work because i am multiplying the scalar after :dot(), because i was unsure if :dot() allows at least one vector to be of length other than one

Say we have two parts, PartA and PartB - we will be calculating the distance according to the former part.

The axis of interest is X-axis, because that’s the axis “traveling from left to the right through a part” in local space.

In the above picture, if we ran the following code, we would get the same distances with different signs. Remember, the blue part (PartA) is located in the origin and its local space matches world space.

local partA = workspace.PartA
local partB = workspace.PartB

print(partB.Position.X) --> -10
print(partB.CFrame:ToObjectSpace(partA.CFrame).Position.X) --> 10

From this point, we can use the second line to see how far on X-axis the green part is from the blue part, regardless of orientation. If we were to rotate both parts, the distance in world space would change, but the distance in local space would remain unchanged.

In object space, PartA is going to be the considered the origin, meaning we can easily read the distance.

local partA = workspace.PartA
local partB = workspace.PartB

local partBObjSpaceCF = partB.CFrame:ToObjectSpace(partA.CFrame)
local distanceX = partBObjSpaceCF.Position.X
print(distanceX)


Of course, other approaches exist. @theseformasentence showed an interesting, more technical approach.

1 Like