When getting the closest point on a part, also center it

Using the following code

local function ClosestPointOnBlock(block: BasePart, point: Vector3): Vector3
	local transform = block.CFrame:PointToObjectSpace(point) -- Transform into local space
	local halfSize = block.Size * 0.5
	return block.CFrame * Vector3.new( -- Clamp & transform into world space
		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

gives me the closest point to a part, which is good, but as shown in the image, it places it on the edge of the part.
image

desired result:
image

how would i achieve this?

1 Like

Not entirely sure if this will solve your problem, however, have you tried finding the width of the target (grey) part using the part’s Z-dimension, halving the width and adding that halved length to the selected (blue) part’s Z-dimension after running the ClosestPointOnBlock function. I could be wrong about using the Z-dimension, it could very well be either the Y or X-dimension that is needed.

That is a good idea, but i’ve tried it. the Grey part is 2 studs wide, so if i add 1 stud to the x dimension of the blue part, it works, but the problem is that the grey part is more like a path, that has 90 degree curves, so if i go to another part of the path, i’d need to apply 1 stud to the z axis ( i think )

Fixed it using the following piece of code to adjust my wall
(closestpart being the grey part)

if closestPoint.X - closestPart.Position.X == -1 then
			closestPoint = closestPoint + Vector3.new(1,0,0)
		elseif closestPoint.X - closestPart.Position.X == 1 then
			closestPoint = closestPoint + Vector3.new(-1,0,0)
		elseif closestPoint.Z - closestPart.Position.Z == 1 then
			closestPoint = closestPoint + Vector3.new(0,0,-1)
		elseif closestPoint.Z - closestPart.Position.Z == -1 then
			closestPoint = closestPoint + Vector3.new(0,0,1)
		end

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.