local partA = workspace.PartA
local partB = workspace.PartB
local function GetOutsidePosition(part1, part2)
local direction = (part2.Position - part1.Position).Unit
local outsidePosition = part1.Position + direction
return outsidePosition
end
local function GetDistance(part1, part2)
local outsidePosition = GetOutsidePosition(part1, part2)
workspace.Point.Position = outsidePosition
local rayOrigin = outsidePosition
local rayDirection = (part2.Position - outsidePosition).Unit * 50
local raycast = workspace:Raycast(rayOrigin, rayDirection)
if raycast then
return raycast.Distance
end
end
local function Update()
local cframe1 = partA.CFrame
local cframe2 = partB.CFrame
local distance = GetDistance(partA, partB)
print(distance)
end
while true do
Update()
task.wait(0.1)
end
Are you talking about getting the distance between the closest sides to 2 parts? For parts with uneven geometry (like meshparts, non-spheres, non-blocks basically), a raycast is probably the best solution.
For blocks,
a quick search with the right question led me to this post:
Basically imagine you’re getting that red vector’s direction only, but you don’t know how long it has to be to reach the edge. You move it beyond the edge but since you know how big your block has to be (why? because you can calculate what coordinates are along the edge with some vector addition from the origin), you clamp it back to the edge.
I before have looked at that post but it didn’t work but now it works now!
local partA = workspace.PartA
local partB = workspace.PartB
local function ClosestPointOnPart(part, point)
local Transform = part.CFrame:PointToObjectSpace(point)
local HalfSize = part.Size / 2
return part.CFrame * Vector3.new(
math.clamp(Transform.x, -HalfSize.x, HalfSize.x),
math.clamp(Transform.y, -HalfSize.y, HalfSize.y),
math.clamp(Transform.z, -HalfSize.z, HalfSize.z)
)
end
local function GetDistance(part1, part2)
local point = ClosestPointOnPart(part1, part2.Position)
workspace.Point.Position = point
local rayOrigin = point
local rayDirection = (part2.Position - rayOrigin).Unit * 50
local raycast = workspace:Raycast(rayOrigin, rayDirection)
if raycast then
return raycast.Distance
end
end
local function Update()
local cframe1 = partA.CFrame
local cframe2 = partB.CFrame
local distance = GetDistance(partA, partB)
print(distance)
end
while true do
Update()
task.wait(0.1)
end