I’m making a physics based game where i want the player to be able to weld together freeform parts (variations of squares) like another game that already exists. In that game it looks like this.
Find the point in 3d space, where the mouse is pointing at, through mouse.Hit.Position
We can just refer to that as “mousePoint”
Now to finding the two parts
We can do this through multiple different methods, but the easiest way by far, at-least in my opinion, would be using Workspace:GetPartBoundsInRadius().
To detect the two parts to weld, what we’d do is get all the parts, within a set radius, such as say .5 studs, from mousePoint, and whichever two weldable parts are closest, we select those two.
Here’s an example of it in use for code:
local mouse = game.Players.LocalPlayer:GetMouse()
local mousePoint = mouse.Hit.Position
-- Setup filter, so only objects in "Workspace.Weldable" are welded.
local params = OverlapParams.new()
params.FilterType = Enum.RaycastFilterType.Include
params.FilterDescendantsInstances = {workspace.Weldable};
-- Perform scan.
local radiusScan = workspace:GetPartBoundsInRadius(mousePoint,0.5,params);
-- Get the two parts from the array.
local firstPart = radiusScan[1];
local secondPart = radiusScan[2];
-- Check if the first and second part exist.
if not firstPart or not secondPart then return end;
-- Weld the two parts together
local weld = Instance.new("WeldConstraint",firstPart);
weld.Part0 = firstPart;
weld.Part1 = secondPart;
Use overlapParams filter out junk, like weld effects, and specifically only allow weldable parts. You don’t have to be limited by just “FilterDescendantsInstances”, you can also filter through other rules like CollisionGroup.