Unity Physics: How To Limit Rotation of Object Mov

2019-07-26 00:07发布

问题:

I have a Child object, an Iron Bar (with Rigidbody and Gravity), connected to a Long Arm (w/ Rigidbody and isKinematic). I need to restrict the rotation of the Iron Bar from 1 to 40 degree angles only so it won't go overboard and hit the Long Arm. Please refer to attached image for more info. I tried several approaches from using a Hinge Joint and its Limit options and also through code. But I cannot seem to solve this problem. Right now I have this script attached to the Iron Bar but it does not seem to have any effect.

public Transform targetTransform;
private Vector3 _currentAngle;
private Vector3 _targetAngle;
float rotationX;

void FixedUpdate () {

     transform.right = targetTransform.transform.right; //-- To make the Iron Bar follow player rotation

     rotationX = transform.eulerAngles.x;

     if (rotationX > 40) {
         _targetAngle = new Vector3 (40, transform.eulerAngles.y, transform.eulerAngles.z);
         _currentAngle = new Vector3 (Mathf.LerpAngle (transform.eulerAngles.x, _targetAngle.x, Time.deltaTime), Mathf.LerpAngle (transform.eulerAngles.y, _targetAngle.y, Time.deltaTime), Mathf.LerpAngle (transform.eulerAngles.z, _targetAngle.z, Time.deltaTime));
         transform.eulerAngles = _currentAngle;
     } else if (rotationX < 1) {
         _targetAngle = new Vector3 (1, transform.eulerAngles.y, transform.eulerAngles.z);
         _currentAngle = new Vector3 (Mathf.LerpAngle (transform.eulerAngles.x, _targetAngle.x, Time.deltaTime), Mathf.LerpAngle (transform.eulerAngles.y, _targetAngle.y, Time.deltaTime), Mathf.LerpAngle (transform.eulerAngles.z, _targetAngle.z, Time.deltaTime));
         transform.eulerAngles = _currentAngle;
     }

 }

Would appreciate any help you can provide. Thanks for taking a look.

Note: This is a revised question but related to the initial one which I have already partially solved. Revision was made for further clarification.