Snap object together

I want to perform a “snap” effect where one object snaps to the other when it is moved close.

I have points of connection for both objects. I want to move the position of object1 so that the point of connection of object1 touches that of object2 (in other words, have the same position).

The points of connection are Vector3. There are many methods for Vector3 available but I’m not sure how to calculate the “snapped” position of object1 using these methods.

Another thing I would like to do is to rotate object1 if it is in the wrong rotation to allow this snapping to happen without overlapping both objects.

I appreciate the help

You could do something like this maybe:

function moveObj(position: THREE.Vector3) {
      
      if(obj.position.distanceTo( obj2.position ) < .01) { // Any value you want .01 = 1cm
         
            position.copy(obj2.position)
      }

      obj.position.copy(position)
}

Thanks for trying to help but unfortunately this does not solve my problem. Please read my post closely as I mentioned all the details.

I coded this task, it seems it is similar with your question


maybe you find there some ideas https://github.com/Dragon3DGraff/room_TestTask

you can try it here
https://dragon3dgraff.ru/room/

@Dragon3DGraff I read your code, but I can’t represent the snap function after I draw.
Can you guide or give me more information?
Thanks,

Anyway, I have a way to snap between object. It will check which face of box1 is closest to box2.
After that, it’ll adjust the position.

moveBoxIfCloset(box1: any, box2: any) {
    if (!box1 || !box2) return
    // Get the position difference between the two boxes
    const dx = box2.position.x - box1.position.x;
    const dy = box2.position.y - box1.position.y;
    const dz = box2.position.z - box1.position.z;
    const box1Scale = box1.scale
    const box2Scale = box2.scale

    // Check which face of box1 is closest to box2
    if (Math.abs(dx) > Math.abs(dy) && Math.abs(dx) > Math.abs(dz)) {
      // Adjust the position of box2 to align with the x-axis
      box2.position.x = box1.position.x + Math.sign(dx) * (box1.geometry.parameters.width * box1Scale.x / 2 + box2.geometry.parameters.width * box2Scale.x / 2);
    } else if (Math.abs(dy) > Math.abs(dx) && Math.abs(dy) > Math.abs(dz)) {
      // Adjust the position of box2 to align with the y-axis
      box2.position.y = box1.position.y + Math.sign(dy) * (box1.geometry.parameters.height * box1Scale.y / 2 + box2.geometry.parameters.height * box2Scale.y / 2);
    } else if(Math.abs(dz) > Math.abs(dx) && Math.abs(dz) > Math.abs(dy)) {
      // Adjust the position of box2 to align with the z-axis
      box2.position.z = box1.position.z + Math.sign(dz) * (box1.geometry.parameters.depth * box1Scale.z / 2 + box2.geometry.parameters.depth * box2Scale.z / 2);
    }
  }