Drag and drop - how to freeze the hit object?

Hello,
I’ve got 2 objects - a sphere and a cube. When I drag the sphere and hit the cube with it, the cube is flying away. How can I make the hit objects stay in the same position even if they are hit with the another (dragged) object? When I checked the Constraints-Freeze Position in Rigidbody, the sphere just went through the cube.

Here is the code I use to drag and drop (both objects have that script attached + rigidbody):

     private bool dragging = false;
     private float distance;
     void OnMouseDown()
     {
         distance = Vector3.Distance(transform.position, Camera.main.transform.position);
         dragging = true;
     }
     void OnMouseUp()
     {
         dragging = false;
     }
     void Update()
     {
         if (dragging)
         {
             Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
             Vector3 rayPoint = ray.GetPoint(distance);
             transform.position = rayPoint;
         }
     }

Because you’re moving the dragged object using ‘transform.position’, your code is overwriting what would be handled by the physics system (the Rigidbody). Throwing constraints is basically just telling the physics system to ignore calculations on those axes, so effectively the same thing but on the other, receiving end.

It sounds to me like you don’t want to be using the physics system at all, and instead just want to be doing detection when two objects collide. This can be done using the OnCollisionEnter method. In that scenario, you wouldn’t have Rigidbodies attached to your objects, and any movement would be handled through code.

1 Like

Alternatively you can move the object with the various AddForce functions. Or possibly by manipulating velocity directly. This would mean the objects movement does not faithfully respect the mouse, but it would interact with other scene objects.