Unity Physics: How To Limit Rotation of Object Moved by Gravity

橙三吉。 提交于 2019-12-11 05:38:45

问题


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.

来源:https://stackoverflow.com/questions/51573517/unity-physics-how-to-limit-rotation-of-object-moved-by-gravity

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!