Set a HingeJoint's Target Position to point toward an object?

I have a hinge joint and I want it’s spring’s TargetAngle to be to where it will point toward an object.
I don’t know how I could go into any more description, so I drew a simple picture.


First, one must calculate the angle to the target. I’ll assume rotation on the Z axis for the moment, because it uses the standard X, Y coordinates common to 2D discussion, but you can choose any axis (or two if you need to create a Quaternion accounting for a 3D angle in other situations).

First, you require a vector to the target point. This is simply something like:

Vector3 v = target - subject;

Where target and subject are Vector3 positions, subject is the position of the hinge pivot point, target is where you want to point. The result is v, a vector3, from which we’ll use the x and y members for Atan2 (next).

In trig, tangent is (in an oversimplified statement) y / x. There’s an implied triangle involved and these are the two legs of that triangle in the y and x axis, where the point we’re ‘getting tangent’ for is at the end of the hypotenuse of this implied right triangle (the other end is at the origin). The inverse trig function gives the angle, in radians, of this tangent. For C# in Unity that is something like:

float a_rad = Mathf.Atan2( v.y, v.x );

Note that some math libraries use x, y, but this one uses y, x, so attend the order with care.

This is in radians, but you’ll probably require degrees, so:

float a_deg = a_rad * Mathf.Rad2Deg;

Converts to degrees. Note, however, this may be an odd orientation to you. It is from straight math, and the Mathf library follows. The angle returned from Atan2 assumes that pointing to the right (a point on the x axis) is zero degrees. Positive rotation results in counter clockwise rotation. You may have to invert this for your application if you assume a rotation that differs. Some assume a ‘clock’ like orientation, where noon is zero and clockwise is positive. You may have to invert with something like:

float a_deg_clockwise = 180 - a_deg;

This assumes you would use Atan’s natural tendency to produce a range of 180 to -180 return values. This inverts counter clockwise into a clockwise rotation, but now 0 degrees is pointing to the negative x axis, which you would then orient as you might require by incrementing or decrementing the angle by 90 degrees, depending on the orientation you prefer. Experiment a bit, because you may have the hinge inverted from what you expect - I can’t see your project from here, but merely recognize that the orientation of Atan2 is standard math, and you may have an alternate view that is related by possibly mirrored or offset by 90 degrees.

The result should be the TargetAngle you require.