Stop Rigidbodies From Overlapping

Okay I have a script which allows objects to be moved with the mouse. The objects have rigidbodies and whenever you place an object on another object they can overlap and cause the object to fly everywhere or get stuck. How can i make it so the rigidbodies/collider do not overlap eachother whenever i try to a object inside another object1378-Untitled.png

The problem is that all the “static” checks are limited to rays, spheres and capsules and can’t do complex shapes. So you have to let pass one frame in order to see if something happened.

Here’s my idea:

If the user dragged an object using the mouse or placed an object, mark this object somehow (i.e. set a boolean flag to true). Implement OnCollisionStart for the dragged/newly created object. If this function gets called and your boolean flag is set to true, you know that something “went wrong”. If nothing gets called, set the flag to false in the first FixedUpdate.

Now you can detect that a dragged or newly placed object overlaps with some other object. You still have to react to that. A possible way would be to reset both objects’ velocity and angular velocity to their old values to prevent them from “exploding” and moving one or both objects along the normal vector of the collision, trying to get them apart.

Move solid rigidbodies by changing their velocity instead of changing their position.

function Update() {
    ...
    heldObject.rigidbody.velocity = (mousePosition - heldObject.transform.position).normalized * desiredMoveSpeed; 
}

Got to “Edit - Project Settings - Physics” and set the “Min Penetration Penalty” to a ridiculous small number, e.g. 0.001

Another option can be that you can set your RigidBody collision Detection mode to “Continuous” or “Continuous Dynamic” for fast objects.