Home > Enterprise >  How to set an objects angle to a HingeJoint2D limit?
How to set an objects angle to a HingeJoint2D limit?

Time:01-12

How can I set the angle of an Object to the limit of a HingeJoint2D? I mean something like this:

gameObject.transform.rotation = HingeJoint2D.limits.max;

CodePudding user response:

Since you're working in 2D, you likely want to set the object's up or right in the direction of the max/min of the hinge.

You can set the object's local up direction to be the same direction as the HingeJoint2D by using Quaternion.LookRotation:

HingeJoint2D hj; // The hinge joint in question
Transform minTransform; // Transform you want to set to point up towards min
Transform maxTransform; // Transform you want to set to point up towards max
Vector3 neutralLocalDir = Vector3.up; // neutral direction of joint. 
                                      // Value to be tuned or calculated in Start

// ...
Vector3 neutral = hj.transform.TransformDirection(neutralLocalDir);
Vector3 minDir = Quaternion.AngleAxis(hj.limits.min, Vector3.forward) * neutral;
minTransform.rotation = Quaternion.LookRotation(Vector3.forward, minDir);

Vector3 maxDir = Quaternion.AngleAxis(hj.limits.max, Vector3.forward) * neutral;
maxTransform.rotation = Quaternion.LookRotation(Vector3.forward, maxDir);

You may be able to use a constant value for neutral or if you need a dynamic value, look into calculating it in Start

CodePudding user response:

Ruzihms solution should just work fine. I another solution by just declaring the transform.rotation.z of a Quaternion to the HingeJoint2D limits, like in the following:

Quaternion minAngle = Quaternion.Euler(transform.rotation.x, transform.rotation.y, hinge.limits.min);
Quaternion maxAngle = Quaternion.Euler(transform.rotation.x, transform.rotation.y, hinge.limits.min);

transform.rotation = maxAngle; //or minAngle :)
  •  Tags:  
  • Related