Search Unity

Keep rigidbody rotation

Discussion in 'Physics' started by Hermonirr, Apr 27, 2020.

  1. Hermonirr

    Hermonirr

    Joined:
    Dec 23, 2013
    Posts:
    56
    I need to keep a rigidbody in the same position and rotation. When it's being pushed by another rigidbody, it should try to return to its initial pose, with a force proportional to the distance / rotation delta from its initial pose.

    This code works very well for the position. The attached file is a short video showing the desired effect.
    The rigidbody rotation is locked.

    Code (CSharp):
    1.  
    2. using UnityEngine;
    3.  
    4. public class Keep_Physics_Pos : MonoBehaviour
    5. {
    6.     private Vector3 startPos;
    7.     public float force = 50;
    8.     Rigidbody rb;
    9.  
    10.     // Start is called before the first frame update
    11.     void Start()
    12.     {
    13.         rb = GetComponent<Rigidbody>();
    14.  
    15.         if(rb == null)
    16.             Destroy(this);
    17.  
    18.         Reset_Pos();
    19.     }
    20.  
    21.     public void Reset_Pos()
    22.     {
    23.         startPos = transform.position;
    24.     }
    25.  
    26.     // FixedUpdate is called once per physics step
    27.     void FixedUpdate()
    28.     {
    29.         float dist = Vector3.Distance(startPos, transform.position);
    30.  
    31.         if(dist > 0.01f)
    32.         {
    33.             rb.velocity = (startPos - transform.position) * force * dist;
    34.         }
    35.     }
    36. }
    37.  
    I can't figure out how to do the same for the rotation.

    Thanks
     

    Attached Files:

  2. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,492
    If you don't want your Dynamic Rigidbody to move then is there a reason to not use its positions constraints or use a Kinematic/Static Rigidbody?

    Is it that you do want it to move but gradually move back to some fixed pose?
     
  3. Hermonirr

    Hermonirr

    Joined:
    Dec 23, 2013
    Posts:
    56
    I do want it to move - in a way. It needs to act kind of like a soft mattress, resisting to external forces lightly at first and then more strongly. The attached video shows the effect I'm looking for.

    Using joints did not work, and since the position can be solved so easily, I wanted to find a similar solution for rotation.
     
  4. MelvMay

    MelvMay

    Unity Technologies

    Joined:
    May 24, 2013
    Posts:
    11,492
    Oh right, sorry I didn't pickup that the .zip file was a video for some reason. I'm not a 3D physics dev but I wonder if the 3D ConfigurableJoint offers enough utility or if you've tried it. You can set XYZ drives to a position and Angular XYZ drives to a rotation and set the force of the spring/damping etc.

    Got to step away now but I'll take a look tomorrow but I think I get the idea.