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.
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)
—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
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
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.