Moving object with mouse drag brakes joints

hello guys.
i’m having some issues with configurable joint.
first of all i have to say i’m not an expert either in unity or coding in general, im learning by doing..

what i need to do is move an object (gun) around a specific object (mount).

the constraints are made with configurable joints.

i’ve made a script that applies forces to the gun and everything works just fine..
if apply too much force the assembly becomes wobling, but stable.

as a second step, i’d like to grab the gun with mouse and move it around..
i have a script that allows me to do the move movements, thanks to a tutorial (https://www.youtube.com/watch?v=0yHBDZHLRbQ), it works great in moving things around, however it breakes the joint phisics.

the gun can move around almost freely, the connection with the mount is still there (the mount moves around randomly trying to catch up with the gun). as soon as i release the mouse everything goes back in place..

here is a vid

i think i’m missing something, either the force of the joint constraints, or a way to keep the phisics working with mouse grab..

any help would be great! :slight_smile:

To do that in a way that respects physics behaviour, including joints, you must only use AddForce and AddTorque to do the movement.

If you use MovePosition or directly change the transform.position these changes bypass the physics simulation as if there were no physics to begin with. The physics simulation may then try to “catch up” or not, either way the behaviour will be incorrect.

You can use AddForceAtPosition to drag the gun around.

so, a potential solution could be:
find the mouse coordinates
extrapolate a vector between current gun pos and desired mouse position.
add force with the extrapolated vector until the two position match using a lerp

at this point it might get bouncy due to force not being applied to actually stop the gun when in the proper position, but maybe a drag value to the rigid body might fix this.

opinions?

using UnityEngine;
public class DragObject : MonoBehaviour
{
    Rigidbody rb;
    Vector3 dragPoint;
    void Start()
    {
        rb = GetComponent<Rigidbody>();
    }

    void OnMouseDown()
    {
        Ray ray = Camera.main.ScreenPointToRay(Input.mousePosition);
        Physics.Raycast(ray, out RaycastHit hit);
        dragPoint = hit.point;
    }

    void OnMouseDrag()
    {
        Vector3 force = (Camera.main.transform.right * Input.GetAxis("Mouse X") + Camera.main.transform.up * Input.GetAxis("Mouse Y")) * 10;
        rb.AddForceAtPosition(force, dragPoint);
    }
}