Forward kinematics computes the endpoint from joint angles; inverse kinematics (IK) computes angles from a target. A two-bone 2D chain has an analytic solution from the law of cosines. Its implementation must handle unreachable targets, degenerate poses and angle conventions.
1. Is the target reachable?
Let the finite bone lengths satisfy a,b > 0, with shoulder S, target T and distance d = ||T-S||. Positions and lengths must use the same Euclidean metric. With fixed lengths, the target is reachable exactly when:
|a - b| <= d <= a + b
If d > a + b, the chain can only point toward the target at full extension. If d < |a-b|, the target lies inside the inner circle that the folded chain cannot reach. Production code clamps d to this interval instead of passing an invalid value to acos.
2. Solve the elbow with the law of cosines
The shoulder, elbow, and target form a triangle. The elbow interior angle gamma satisfies:
cos(gamma) = (a^2 + b^2 - d^2) / (2ab)
gamma = acos(clamp(cos(gamma), -1, 1))
Use counterclockwise positive angles and store the forearm angle relative to the upper arm. If the shoulder angle is phi + s*alpha, the relative elbow angle is -s*(pi-gamma), with s equal to ±1. A downward screen y-axis requires a consistent change of the full convention.
3. Solve the shoulder and preserve elbow direction
The target direction is phi = atan2(Ty-Sy, Tx-Sx). The shoulder triangle angle is:
alpha = acos((a^2 + d^2 - b^2) / (2ad))
shoulder = phi +/- alpha
The plus and minus choices are mirror solutions: elbow-up and elbow-down. A rig must preserve a pole direction or elbow sign. Otherwise, the elbow can flip suddenly when the target crosses the bone line.
4. Numerical example
Use a=150, b=125, and target distance d=200:
cos(gamma) = (150^2 + 125^2 - 200^2) / (2*150*125)
= -0.05
gamma = acos(-0.05) = 92.87°
cos(alpha) = (150^2 + 200^2 - 125^2) / (2*150*200)
= 0.78125
alpha = 38.62°
Adding target direction phi gives the shoulder angle and elbow position. Drag the blue target below and change both bone lengths. Move the target beyond the reachable circle to see the solution clamp to full extension.
Geometry · IK
Two-Bone Inverse Kinematics
Use the law of cosines to solve shoulder and elbow angles, unreachable targets, and elbow flips.
Drag the blue target
5. Boundary handling for analytic IK
- Floating-point error: clamp every cosine to
[-1, 1]before callingacos. - Near full extension: the two solutions converge, so preserve the previous frame’s elbow sign.
- Target crosses the shoulder: use
atan2, notatan(y/x), to preserve quadrant information. - Joint limits: solve analytically, constrain shoulder and elbow angles, and then recompute the end point.
6. Boundary cases and expected results
With a=150 and b=125, the reachable distance is [25, 275]. Targets on both sides of that interval test clamping, floating-point protection, and elbow continuity together.
| Raw distance d | Solve distance | Expected pose | Required check |
|---|---|---|---|
| 300 | 275 | Fully extended toward the target | The end stays on the outer circle and cosine does not exceed 1 |
| 200 | 200 | Elbow interior angle about 92.87° | Both mirror solutions reach the same end point |
| 25 | 25 | Maximum folded boundary | No jump from a small denominator |
| 0 | 25 | Stable fold along the previous direction | Do not compute the shoulder offset from zero distance |
| Target crosses the bone line | Unchanged | Saved elbow sign selects the side | No mirror flip between adjacent frames |
7. Original pseudocode and corrected solver
The original pseudocode is retained below for comparison. Its shoulder and relative elbow angles use the same sign, which misses the target under the convention above. Its eps also shrinks the reachable interval; the resulting pose change depends on scale and tolerance. The table describes ideal closed-interval boundaries. The following Python version corrects the sign and handles the degenerate equal-length case with the target at the root.
delta = target - shoulder
raw_d = length(delta)
direction = raw_d > eps ? delta / raw_d : previous_direction
d = clamp(raw_d, abs(a - b) + eps, a + b - eps)
cos_elbow = clamp((a*a + b*b - d*d) / (2*a*b), -1, 1)
cos_offset = clamp((a*a + d*d - b*b) / (2*a*d), -1, 1)
phi = atan2(direction.y, direction.x)
shoulder_angle = phi + elbow_sign * acos(cos_offset)
elbow_angle = elbow_sign * (pi - acos(cos_elbow))
Corrected solver and boundary checks:
from math import acos, atan2, cos, sin, hypot, pi, isfinite
def solve_two_bone(a, b, dx, dy, side=1, preferred_angle=0.0):
"""Positive angles are counterclockwise; elbow is relative to upper arm."""
if not all(isfinite(x) for x in (a, b, dx, dy, preferred_angle)):
raise ValueError("finite inputs required")
if a <= 0 or b <= 0 or side not in (-1, 1):
raise ValueError("positive lengths and side +/-1 required")
raw = hypot(dx, dy)
phi = atan2(dy, dx) if raw else preferred_angle
d = min(max(raw, abs(a - b)), a + b)
if d == 0: # equal lengths folded onto the root
return phi, -side * pi, (0.0, 0.0)
clip = lambda x: min(1.0, max(-1.0, x))
alpha = acos(clip((a*a + d*d - b*b) / (2*a*d)))
gamma = acos(clip((a*a + b*b - d*d) / (2*a*b)))
shoulder = phi + side * alpha
elbow = -side * (pi - gamma)
return shoulder, elbow, (d*cos(phi), d*sin(phi))
def forward(a, b, shoulder, elbow):
return (a*cos(shoulder) + b*cos(shoulder + elbow),
a*sin(shoulder) + b*sin(shoulder + elbow))
if __name__ == "__main__":
for a, b in ((150.0, 125.0), (125.0, 150.0), (100.0, 100.0)):
for distance in (0.0, abs(a-b), abs(a-b)+1e-4,
(a+b)/2, a+b-1e-4, a+b, a+b+20):
for phi in (-2.1, 0.0, 1.3):
for side in (-1, 1):
sh, el, target = solve_two_bone(
a, b, distance*cos(phi), distance*sin(phi), side)
end = forward(a, b, sh, el)
assert hypot(end[0]-target[0], end[1]-target[1]) < 1e-5
print("TWO_BONE_IK_CHECKED")
The snap at full extension: softening the reach limit
Beyond maximum reach, a fixed-length chain remains straight. For a softer approach, map the input target distance to a softened distance before solving IK.
Let L=a+b and choose a softening width 0 < s < L-|a-b|. Apply this mapping to the raw target distance, then enforce the inner reach limit:
if d < L - s:
d_soft = d # far from the limit, pass through
else:
d_soft = L - s * exp(-(d - (L - s)) / s)
At d=L-s, the value and first derivative match; the second derivative is generally discontinuous. In exact real arithmetic, finite inputs yield d_soft < L, approaching L asymptotically. Floating-point rounding can produce L. Enforce a minimum bend angle or distance margin separately when the rig requires one.
A width of 3%–8% of total length is an illustrative tuning range. Choose it using the character proportions, target trajectory and permitted endpoint error. A wider soft zone makes the endpoint lag behind the target over more of the working range.
The inner bound |a-b| needs a separate softening map with continuity and reachability checks. The outer exponential formula cannot be applied there unchanged.
Declare which space the target lives in
Transform the shoulder and target into the space in which bone lengths are defined. Nonuniform parent scaling changes the distance metric: transformed positions cannot simply be combined with unscaled bone lengths. Solve in a suitable orthonormal frame with consistent lengths.
For a foot planted on the ground, the target belongs in world space: the body moves forward and the foot stays put until the next step. That is precisely how foot sliding is avoided.
For a hand resting on a hip, the target belongs in character space: as the character walks, the hand travels with the body. Store that target in world coordinates and the moment the character moves the hand stays behind, stretching out as if pinned to the air.
For a hand on a moving door, the target belongs in the door’s space — neither world nor character.
So an IK target cannot be stored as coordinates alone; it needs its parent space alongside:
{ "target": [120, 40], "space": "world" } # planted foot
{ "target": [18, -30], "space": "character" } # hand on hip
{ "target": [4, 12], "space": "door_handle" } # hand on a door
Transform the target into the shoulder’s space before solving, then apply the formulas above. Structurally this step is input preparation rather than part of the solve, which is exactly why it tends to get written at each call site and end up inconsistent.
When diagnosing foot sliding, first check whether the target stays fixed in its intended space. Then inspect gait targets, root motion, reach limits and the solver residual.
Joint limits and endpoint error
Clamping solved angles to the rig limits usually changes the endpoint. Run forward kinematics again and record the actual error.
For a nondegenerate pose, selecting an elbow direction chooses the corresponding analytic solution. Joint limits can then break the target constraint. Degenerate poses and full-turn equivalent angles need separate handling. Choose an error strategy for the animation:
Accept the error. The hand stops short, leaving a gap to the target. Fine when the target is only a guide — gaze following, for instance — and wrong when the hand is supposed to hold a specific object, because the audience sees the hand separate from the cup.
Move the root. Shift the shoulder, or the whole body, toward the target until the hand can reach. This is what a real body does — you lean when something is out of reach. The cost is that moving the root affects everything else, so the offset needs limiting and smoothing, or the body jitters along with the hand.
Allow lengths to vary within an explicit range, using ±10% as an illustrative starting range if suitable. Acceptable stretch depends on the artwork and motion. Inspect the deformation in playback and record the bounds in the rig configuration.
Record the error strategy, joint ranges and stretch bounds in the rig configuration, and apply the same rule whenever a target or joint limit is reached.
Record endpoint distance to both the original target and the clamped or softened target. With a reachable target and no further constraints, the analytic residual should approach the numerical tolerance. Larger residuals call for checks of softening, joint limits, coordinate transforms and implementation errors.
Target noise and angle sensitivity near reach limits
Analytic IK becomes more sensitive to target perturbations near degenerate poses. The angle change depends on lengths, distance and perturbation direction; one pixel does not imply a fixed ten-degree change. The derivative of acos explains the sensitivity:
d/dx acos(x) = -1 / sqrt(1 - x^2)
The derivative magnitude diverges as x approaches ±1. For the elbow-interior cosine x=(a²+b²-d²)/(2ab), full extension gives x=-1 and the inner folded boundary gives x=1. The shoulder offset uses a different cosine ratio. Equal lengths at d=0 also leave the target direction undefined.
Test trajectories near extension, near the inner boundary and through the root. Record input perturbations and angle changes separately. Visible jitter also depends on precision, target noise and angle continuity handling.
Outer soft IK changes the distance response near extension, but an asymptotic mapping does not provide a fixed safety margin. Combine it with numerical tolerances, a minimum bend if required and pose-continuity checks.
For noisy target input, filtering positions before IK can help; check the added latency. Filtering solved angles is another animation choice, but it changes the endpoint constraint. Reproject onto the permitted pose when required.
8. Analytic IK versus CCD and FABRIK
The analytic two-bone solution has fixed computational cost and is easy to check. Longer chains can use CCD or FABRIK. Each method needs reachability, joint-limit, numerical-stability and temporal-continuity checks.
9. Next: deform the artwork continuously around the joint
IK changes the bone pose but does not repair layer seams. Linear Blend Skinning and Seam Control binds nearby mesh vertices to both bones and explains white dots, cracks, and joint collapse. The prerequisite is Skeletal Transforms and Forward Kinematics.