How to make part clamp?

Hi everyone!
I am creating a game that includes the movement of a part based on the player’s mouse position. However, I have run into a slight problem because I can’t figure out how I would make the part clamp if it were near a tower. Down below I have a video of the system I made plus the code that controls it.

connection = game:GetService("RunService").RenderStepped:Connect(function()
		
		start = selected.Tower.CFrame
		local pos = mouse.Hit.p
		local distance = (start.p - pos).magnitude 


		if distance > 50 then
			distance = 50
		end



		p.Size = Vector3.new(p.Size.X, p.Size.Y, distance)
		p.CFrame = CFrame.new(Vector3.new(start.p.X, 0.1, start.p.Z), Vector3.new(pos.X, 0.1, pos.Z)) * CFrame.new(0, 0, -distance / 2)

		

end)	

Thank you!