Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Chapter 3: Kinematics in 2D

In this chapter, we will use the planar 2R robot as a running example to introduce the basic kinematics concepts for robotic systems. The key advantage of working in 2D is that all essential concepts — forward kinematics, inverse kinematics, and velocity kinematics — can be understood using elementary trigonometry before generalizing to 3D in Chapter 4.

The chapter is organized as follows:

  • Section 3.1 introduces the 2R robot and its parameters.

  • Section 3.2 solves forward and inverse position kinematics using pure geometry.

  • Section 3.3 derives velocity kinematics by differentiating the position equations, leading to the Jacobian.

3.1 A 2D Planar Robot

A planar 2R robot has two rigid links connected by two revolute (rotary) joints, with all motion confined to a plane.

Parameters:

SymbolMeaning
l1l_1Length of link 1
l2l_2Length of link 2
θ1\theta_1Angle of joint 1, measured from the positive xx-axis
θ2\theta_2Angle of joint 2, measured relative to the direction of link 1

Why is θ2\theta_2 relative to link 1, not the global xx-axis?
Because joint 2 is physically mounted on link 1. When joint 1 rotates, the whole second link rotates with it — so measuring θ2\theta_2 from link 1’s direction captures the actual rotation at that joint. The absolute angle of link 2 in the global frame is θ1+θ2\theta_1 + \theta_2.

Key positions:

  • Base: p0=(0, 0)\mathbf{p}_0 = (0,\ 0)

  • Elbow: p1=(l1cos⁡θ1, l1sin⁡θ1)\mathbf{p}_1 = (l_1\cos\theta_1,\ l_1\sin\theta_1)

  • End-effector: p2=(x, y)\mathbf{p}_2 = (x,\ y)

In the widget below, the dashed lines show the reference direction each angle is measured from. The arcs show the actual angles.

<Figure size 600x600 with 1 Axes>

Key Takeaways — Section 3.1

  • The 2R robot has four parameters: l1l_1, l2l_2, θ1\theta_1, θ2\theta_2.

  • θ2\theta_2 is measured relative to link 1, not the global xx-axis. The absolute angle of link 2 is θ1+θ2\theta_1 + \theta_2.

  • The reachable workspace is an annulus: inner radius ∣l1−l2∣|l_1 - l_2|, outer radius l1+l2l_1 + l_2.

3.2 Position Kinematics

Position kinematics addresses two complementary problems:

  • Forward kinematics (FK): Given (θ1,θ2)(\theta_1, \theta_2), find the end-effector position (x,y)(x, y).

  • Inverse kinematics (IK): Given desired (x,y)(x, y), find (θ1,θ2)(\theta_1, \theta_2).

FK is always unique and straightforward. IK is more challenging — for the 2R robot there are generally two solutions for each reachable target, corresponding to the elbow-down and elbow-up configurations.

3.2.1 Forward Kinematics

The end-effector position is found by summing the vector contribution of each link.

  • Link 1 has length l1l_1 and points at angle θ1\theta_1 from the xx-axis.

  • Link 2 has length l2l_2 and points at angle θ1+θ2\theta_1 + \theta_2 from the xx-axis (because θ2\theta_2 is measured from link 1, which is already rotated by θ1\theta_1).

x=l1cos⁡θ1+l2cos⁡(θ1+θ2)\boxed{x = l_1 \cos\theta_1 + l_2 \cos(\theta_1 + \theta_2)}
y=l1sin⁡θ1+l2sin⁡(θ1+θ2)\boxed{y = l_1 \sin\theta_1 + l_2 \sin(\theta_1 + \theta_2)}

Sanity check: Set θ1=90°\theta_1 = 90°, θ2=0°\theta_2 = 0°. Both links point straight up, so we expect x=0x = 0, y=l1+l2y = l_1 + l_2. Plugging in: x=l1cos⁡90°+l2cos⁡90°=0x = l_1\cos 90° + l_2\cos 90° = 0 ✓, y=l1sin⁡90°+l2sin⁡90°=l1+l2y = l_1\sin 90° + l_2\sin 90° = l_1 + l_2 ✓.

θ₁ = 45°, θ₂ = 60°  →  End-effector: (0.5001, 1.4798) m

Sanity checks:
  θ₁=   0°, θ₂=   0°:  (1.8000, 0.0000)   Both links along +x  →  expect (1.8, 0.0)
  θ₁=  90°, θ₂=   0°:  (0.0000, 1.8000)   Both links straight up  →  expect (0.0, 1.8)
  θ₁=   0°, θ₂= 180°:  (0.2000, 0.0000)   Link 2 folds back  →  expect (0.2, 0.0)  [= l₁−l₂]
  θ₁=  90°, θ₂= -90°:  (0.8000, 1.0000)   Link 2 points in +x at elbow  →  expect (0.8, 1.0)

Workspace of the Planar 2R Robot

The workspace is the set of all end-effector positions (x,y) the robot can reach as its joints move through their allowed angles.

For the 2R planar robot in this notebook (l_1=1.0), (l_2=0.8):

  • Maximum reach (arm fully stretched):

    rmax⁡=l1+l2=1.8r_{\max}=l_1+l_2=1.8
  • Minimum reach (arm folded back):

    rmin⁡=∣l1−l2∣=0.2r_{\min}=|l_1-l_2|=0.2

So the reachable region is an annulus (ring) centered at the base:

0.2≤x2+y2≤1.80.2 \le \sqrt{x^2+y^2} \le 1.8

In the code below, plot_workspace() samples many (θ1\theta_1,θ2\theta_2) pairs, computes FK points (X,Y), and visualizes this ring-shaped reachable set with inner and outer boundary circles.

<Figure size 600x600 with 1 Axes>

Key Takeaways — Section 3.2.1

  • FK just sums the two link vectors: x=l1cos⁡θ1+l2cos⁡(θ1+θ2)x = l_1\cos\theta_1 + l_2\cos(\theta_1+\theta_2), same for yy.

  • The absolute angle of link 2 in the global frame is θ1+θ2\theta_1 + \theta_2, not θ2\theta_2.

  • The workspace is an annulus with inner radius ∣l1−l2∣|l_1 - l_2| and outer radius l1+l2l_1 + l_2.

Math Tool: atan2

The inverse kinematics derivation uses atan2(y, x) rather than the ordinary atan(y/x). Here is why:

  • atan(y/x) only returns values in (−90°,+90°)(-90°, +90°) and fails when x=0x = 0.

  • atan2(y, x) returns the angle of the vector (x,y)(x, y) in the full range (−180°,+180°](-180°, +180°], correctly handling all four quadrants.

atan2(y, x)result
atan2(0, 1)0°
atan2(1, 0)90°
atan2(0, -1)180°
atan2(-1, 0)-90°
atan2(1, 1)45°
atan2(1, -1)135°
atan2(-1, 1)-45°
atan2(y, x) returns the angle of the vector (x, y) in [-180°, +180°]:

  atan2( 0,  1) =     0.0°
  atan2( 1,  0) =    90.0°
  atan2( 0, -1) =   180.0°
  atan2(-1,  0) =   -90.0°
  atan2( 1,  1) =    45.0°
  atan2(-1,  1) =   -45.0°
  atan2( 1, -1) =   135.0°

Compare with atan(y/x) — wrong quadrant when x < 0:
  y=-1, x=-1:  atan2 = -135.0°  (correct),  atan = 45.0°  (wrong quadrant)
  y= 1, x=-1:  atan2 = 135.0°  (correct),  atan = -45.0°  (wrong quadrant)

3.2.2 Inverse Kinematics

Physical picture first: Think of the base, elbow, and end-effector as a triangle. The side lengths are l1l_1, l2l_2, and r=x2+y2r = \sqrt{x^2+y^2} (distance from base to target). The angle at the base of this triangle depends on rr, l1l_1, l2l_2 — but not on the direction atan2(y,x)\text{atan2}(y,x) to the target. This means we can find θ2\theta_2 from the distance alone, then find θ1\theta_1 using the direction. There are two triangles for the same side lengths (flip the elbow), giving the two solutions.


Step 1 — Find θ2\theta_2

Square and add the FK equations:

x2+y2=[l1cos⁡θ1+l2cos⁡(θ1+θ2)]2+[l1sin⁡θ1+l2sin⁡(θ1+θ2)]2x^2 + y^2 = [l_1\cos\theta_1 + l_2\cos(\theta_1+\theta_2)]^2 + [l_1\sin\theta_1 + l_2\sin(\theta_1+\theta_2)]^2

Expanding (cross terms use the cosine-subtraction identity cos⁡Acos⁡B+sin⁡Asin⁡B=cos⁡(A−B)\cos A\cos B + \sin A\sin B = \cos(A-B)):

=l12(cos⁡2θ1+sin⁡2θ1)+l22(cos⁡2(θ1+θ2)+sin⁡2(θ1+θ2))+2l1l2cos⁡θ2= l_1^2(\cos^2\theta_1 + \sin^2\theta_1) + l_2^2(\cos^2(\theta_1+\theta_2) + \sin^2(\theta_1+\theta_2)) + 2l_1 l_2\cos\theta_2

=l12+l22+2l1l2cos⁡θ2= l_1^2 + l_2^2 + 2l_1 l_2\cos\theta_2

Solving:

cos⁡θ2=x2+y2−l12−l222l1l2\cos\theta_2 = \frac{x^2 + y^2 - l_1^2 - l_2^2}{2l_1 l_2}

Since sin⁡2θ2+cos⁡2θ2=1\sin^2\theta_2 + \cos^2\theta_2 = 1, there are two solutions for θ2\theta_2 (positive and negative square root):

θ2=atan2 ⁣(±1−cos⁡2θ2, cos⁡θ2)\theta_2 = \text{atan2}\!\left(\pm\sqrt{1 - \cos^2\theta_2},\ \cos\theta_2\right)

Reachability: If ∣cos⁡θ2∣>1|\cos\theta_2| > 1 the target is outside the workspace — no solution exists.


Step 2 — Find θ1\theta_1

With θ2\theta_2 known, define:

α=atan2(y, x)(direction from base to target)\alpha = \text{atan2}(y,\ x) \quad\text{(direction from base to target)}

β=atan2(l2sin⁡θ2, l1+l2cos⁡θ2)(correction angle due to link 2)\beta = \text{atan2}(l_2\sin\theta_2,\ l_1 + l_2\cos\theta_2) \quad\text{(correction angle due to link 2)}

Then:

θ1=α−β\theta_1 = \alpha - \beta

The two values of θ2\theta_2 (positive/negative) give two values of β\beta, yielding the elbow-down and elbow-up solutions.

Target: (1.0, 0.8)
  Elbow-down: θ₁=   0.00°,  θ₂=  90.00°  →  FK check (1.0000, 0.8000)
  Elbow-up  : θ₁=  77.32°,  θ₂= -90.00°  →  FK check (1.0000, 0.8000)
<Figure size 1200x500 with 2 Axes>

Key Takeaways — Section 3.2.2

  • Squaring and adding the FK equations eliminates θ1\theta_1 and gives a direct formula for cos⁡θ2\cos\theta_2.

  • Two solutions exist because sin⁡θ2=±1−cos⁡2θ2\sin\theta_2 = \pm\sqrt{1-\cos^2\theta_2} (elbow-down and elbow-up).

  • Once θ2\theta_2 is known, θ1=atan2(y,x)−β\theta_1 = \text{atan2}(y,x) - \beta where β\beta accounts for link 2’s offset.

  • Use atan2, not atan, to handle all quadrants correctly.

Practice Problems — Section 3.2

  1. Compute FK for θ1=30°\theta_1 = 30°, θ2=90°\theta_2 = 90°, l1=1l_1 = 1, l2=0.8l_2 = 0.8. Verify with the code.

  2. Is the target (1.5, 0.5)(1.5,\ 0.5) reachable? Find both IK solutions and confirm with FK.

  3. What happens to the inner workspace radius when l1=l2l_1 = l_2? What does this mean for IK at that boundary?

  4. Try an unreachable target in ik_interactive. Where exactly is the boundary between reachable and unreachable?

3.3 Velocity Kinematics

The Jacobian relates the joint velocities to the end-effector’s velocity. Specifically, it answers the question “if the joints rotate at certain speeds, how fast does the end-effector move?” It is the matrix that linearly maps joint velocities (θ˙1,θ˙2)(\dot{\theta}_1, \dot{\theta}_2) to end-effector velocity (x˙,y˙)(\dot{x}, \dot{y}). Like all derivatives, it is only valid instantaneously at the current configuration — the robot’s shape changes the relationship.

Differentiating the FK equations with respect to time (chain rule):

x˙=[−l1sin⁡θ1−l2sin⁡(θ1+θ2)]θ˙1+[−l2sin⁡(θ1+θ2)]θ˙2\dot{x} = \bigl[-l_1\sin\theta_1 - l_2\sin(\theta_1+\theta_2)\bigr]\dot{\theta}_1 + \bigl[-l_2\sin(\theta_1+\theta_2)\bigr]\dot{\theta}_2
y˙=[l1cos⁡θ1+l2cos⁡(θ1+θ2)]θ˙1+[l2cos⁡(θ1+θ2)]θ˙2\dot{y} = \bigl[l_1\cos\theta_1 + l_2\cos(\theta_1+\theta_2)\bigr]\dot{\theta}_1 + \bigl[l_2\cos(\theta_1+\theta_2)\bigr]\dot{\theta}_2

In matrix form:

[x˙y˙]=[−l1sin⁡θ1−l2sin⁡(θ1+θ2)−l2sin⁡(θ1+θ2)l1cos⁡θ1+l2cos⁡(θ1+θ2)l2cos⁡(θ1+θ2)]⏟J(θ)[θ˙1θ˙2]\begin{bmatrix}\dot{x}\\\dot{y}\end{bmatrix} = \underbrace{\begin{bmatrix}-l_1\sin\theta_1-l_2\sin(\theta_1+\theta_2) & -l_2\sin(\theta_1+\theta_2)\\ l_1\cos\theta_1+l_2\cos(\theta_1+\theta_2) & l_2\cos(\theta_1+\theta_2)\end{bmatrix}}_{\mathbf{J}(\theta)}\begin{bmatrix}\dot{\theta}_1\\\dot{\theta}_2\end{bmatrix}

Column interpretation: Each column of J\mathbf{J} is the end-effector velocity produced when only that joint moves at 1 rad/s:

  • Column 1 (θ˙1=1,θ˙2=0\dot{\theta}_1=1, \dot{\theta}_2=0): both links swing with joint 1, so the EE velocity has contributions from both.

  • Column 2 (θ˙1=0,θ˙2=1\dot{\theta}_1=0, \dot{\theta}_2=1): only link 2 swings, so only link 2 contributes.

Singularities: det⁡(J)=l1l2sin⁡θ2\det(\mathbf{J}) = l_1 l_2\sin\theta_2.
This is zero when θ2=0°\theta_2 = 0° (arm fully extended) or θ2=±180°\theta_2 = \pm 180° (arm fully folded back). At these configurations the two links are collinear and the robot cannot move the end-effector perpendicular to that line — it has temporarily lost one degree of freedom.

Jacobian at θ₁=45°, θ₂=60°:
[[-1.4798 -0.7727]
 [ 0.5001 -0.2071]]

Column interpretation:
  Only θ̇₁=1 rad/s  →  EE velocity = [-1.4798  0.5001] m/s  (= col 1 of J)
  Only θ̇₂=1 rad/s  →  EE velocity = [-0.7727 -0.2071] m/s  (= col 2 of J)

With θ̇₁=0.5, θ̇₂=-0.3 rad/s  →  EE velocity = [-0.5081  0.3121] m/s

det(J) = 0.6928
l₁ l₂ sin(θ₂) = 0.6928  (should match)

Physical meaning — v_ee = J1·θ̇₁ + J2·θ̇₂:
  J1 = [-1.4798  0.5001]  (joint 1's direction, |J1| = 1.5620)
  J2 = [-0.7727 -0.2071]  (joint 2's direction, |J2| = 0.8000)
  J1 · θ̇₁ = [-0.7399  0.25  ] m/s   (joint 1's contribution)
  J2 · θ̇₂ = [0.2318 0.0621] m/s   (joint 2's contribution)
  Sum      = [-0.5081  0.3121] m/s   (matches v_ee above ✓)

Physical Meaning: the Jacobian as a Sum of Joint Contributions

Split J\mathbf{J} into its two columns, J=[J1J2]\mathbf{J} = \begin{bmatrix}\mathbf{J}_1 & \mathbf{J}_2\end{bmatrix}. The matrix-vector product then reads as a vector sum:

p˙=Jθ˙=J1 θ˙1  +  J2 θ˙2\dot{\mathbf{p}} = \mathbf{J}\dot{\boldsymbol\theta} = \mathbf{J}_1\,\dot\theta_1 \;+\; \mathbf{J}_2\,\dot\theta_2

Each term is one joint’s contribution to the end-effector velocity, and each contribution has a clean direction/magnitude split:

  • J1\mathbf{J}_1 is a direction — the vector the end-effector would move along if joint 1 alone spun at 1 rad/s. It depends only on the current configuration (θ1,θ2)(\theta_1,\theta_2), not on how fast the joints are actually moving.

  • θ˙1\dot\theta_1 is the magnitude — it stretches, shrinks, or reverses that fixed direction. A negative θ˙1\dot\theta_1 just flips J1\mathbf{J}_1 to point the other way.

  • Likewise, J2 θ˙2\mathbf{J}_2\,\dot\theta_2 is joint 2’s contribution: direction J2\mathbf{J}_2, scaled by θ˙2\dot\theta_2.

  • The true end-effector velocity p˙\dot{\mathbf{p}} is what you get by placing these two contributions tip-to-tail and drawing the arrow from the start to the final point — ordinary vector addition.

This is exactly what matrix-vector multiplication is, viewed geometrically: Jθ˙\mathbf{J}\dot{\boldsymbol\theta} scales each column by its matching component of θ˙\dot{\boldsymbol\theta} and adds the results. The plot below draws the two contributions tip-to-tail (in steel blue and tomato, matching the link colors) alongside the resultant p˙\dot{\mathbf{p}} (dashed purple) for the same numbers used above.

<Figure size 1300x650 with 2 Axes>
<Figure size 700x700 with 1 Axes>

Key Takeaways — Section 3.3

  • The Jacobian J(θ)\mathbf{J}(\theta) linearly maps joint velocities to end-effector velocity: p˙=Jθ˙\dot{\mathbf{p}} = \mathbf{J}\dot{\boldsymbol{\theta}}.

  • Column ii of J\mathbf{J} is the EE velocity when only joint ii rotates at 1 rad/s.

  • det⁡(J)=l1l2sin⁡θ2\det(\mathbf{J}) = l_1 l_2 \sin\theta_2: zero when the arm is fully extended or fully folded.

  • At a singularity the robot cannot move in one Cartesian direction, no matter what the joints do.

Practice Problems — Section 3.3

  1. At θ1=0°\theta_1 = 0°, θ2=90°\theta_2 = 90°, compute J\mathbf{J} by hand and verify with the code.

  2. Slide θ2\theta_2 slowly toward 0°0° in velocity_interactive. What happens to the velocity arrow and why?

  3. Find a configuration where joint 1 rotation produces no xx-velocity at the end-effector. What does the robot look like?

  4. If the desired EE velocity is (x˙,y˙)=(1,0)(\dot{x},\dot{y}) = (1, 0), what joint velocities are required at θ1=0°\theta_1=0°, θ2=90°\theta_2=90°? (Hint: compute J−1\mathbf{J}^{-1} at that configuration.)

3.4 Simulating the 2R Robot using MuJoCo

MuJoCo is a physics engine widely used for robotics simulation and control. It provides efficient computation of kinematics, dynamics, and collisions. In this section, we use MuJoCo as a kinematics engine — without advancing time, so the physics only computes geometry — to validate the forward kinematics formulas we derived in Sections 3.2 and 3.3. You can find an introductory tutorial here: MuJoCo Tutorial.

We build the same 2R arm (l1=1.0l_1 = 1.0 m, l2=0.8l_2 = 0.8 m) defined in MJCF (MuJoCo XML Format). In practice, robot models come from CAD software (SolidWorks, Fusion 360) → STL mesh export → URDF description → MJCF conversion. Here we write the XML by hand so every element is explicit and readable.

Three objects appear throughout every MuJoCo program:

ObjectWhat it represents
MjModelStatic robot structure — bodies, joints, geometries, sensors. Loaded once from XML; never changes during a run.
MjDataTime-varying state — joint angles (qpos), velocities (qvel), body poses (xpos, xmat), forces.
mj_forward(model, data)Given angles in data.qpos, propagates the kinematic chain and writes every body’s world-frame position into data.xpos.

3.4.1 Defining the Robot in MJCF

An MJCF file is a plain-text XML file that describes the robot completely. The elements we need for a 2R arm:

ElementRole
<body>A rigid link. Nest bodies inside each other to form a kinematic chain.
<joint>Adds one degree of freedom: how this body moves relative to its parent. For a revolute joint use type="hinge".
<geom>A geometric shape (capsule, sphere, box, …) used for rendering and collision.
<camera>A virtual viewpoint. We add a top-down camera to view the planar robot from above.

Kinematic tree — XML nesting mirrors the physical chain:

worldbody
└── link1  ← joint1: hinge around z, relative to world
    └── link2  ← joint2: hinge around z, relative to link1
        └── end_effector  ← rigidly fixed to link2 (no joint)

Key rule: the pos="…" attribute of a <body> sets its origin in its parent’s local frame.
Writing pos="1.0 0 0" for link2 means “my origin is 1 m along link1’s local x-axis” — exactly the elbow.

The code cell below writes out the full MJCF, loads it into MuJoCo, and prints the resulting model structure.

=== Model summary ===
  Bodies (including world):  4
  Joints:                    2
  qpos size:                 2

=== Body index — data.xpos[id] gives world-frame (x, y, z) ===
  body[0]  'world'
  body[1]  'link1'
  body[2]  'link2'
  body[3]  'end_effector'

'end_effector' id = 3  ->  data.xpos[3] = EE world position
'link2'        id = 2  ->  data.xpos[2] = elbow world position

3.4.2 Forward Kinematics with MuJoCo

The MuJoCo FK workflow is always the same three lines — and will look identical whether the robot has 2 joints or 20:

data.qpos[0] = theta1           # 1. write joint angles in radians
data.qpos[1] = theta2
mujoco.mj_forward(model, data)  # 2. propagate the kinematic chain
ee_pos = data.xpos[ee_id]       # 3. read any body's world-frame position

data.xpos is a NumPy array with shape (nbody, 3). After mj_forward, row i holds the (x, y, z) world-frame position of body i’s origin.

The cell below computes the end-effector position for several configurations and compares all three FK methods side by side.

End-effector (x, y) in metres — three methods compared:
  Config                         Geometric            MuJoCo  Match
────────────────────────────────────────────────────────────────────────────────────
  θ₁=  45°, θ₂=  60°   ( 0.500, 1.480)   ( 0.500, 1.480)       ✓
  θ₁=   0°, θ₂=   0°   ( 1.800, 0.000)   ( 1.800, 0.000)       ✓
  θ₁=  90°, θ₂=   0°   ( 0.000, 1.800)   ( 0.000, 1.800)       ✓
  θ₁=   0°, θ₂= 180°   ( 0.200, 0.000)   ( 0.200, 0.000)       ✓
  θ₁=  30°, θ₂= -60°   ( 1.559, 0.100)   ( 1.559, 0.100)       ✓
  θ₁=  90°, θ₂= -90°   ( 0.800, 1.000)   ( 0.800, 1.000)       ✓

Both methods return the same end-effector position ✓

The advantage of MuJoCo: no re-derivation needed for any new robot —
define the MJCF, load it, and call mj_forward().

Bonus — elbow (link2 origin) at θ₁=45°, θ₂=60°: (0.7071, 0.7071)  m
  Compare with geometric:  l₁·cos(θ₁) = 0.7071,  l₁·sin(θ₁) = 0.7071  ✓

Bonus: A Live 3D Viewer (local only)

mujoco.viewer.launch_passive() opens an actual desktop window that a slider can drive in real time — genuinely interactive, but it needs a local display and a running Python kernel, so it can’t be reproduced on this static page. Download the notebook and run the cell below yourself to try it:

import mujoco.viewer          # requires mujoco >= 2.2.0
from ipywidgets import interact, FloatSlider

# mujoco.viewer.launch_passive() opens a 3D viewer window WITHOUT blocking
# the notebook -- you can keep running cells while the window is open.
#
# Inside the viewer window you can:
#   Left-click + drag    -- rotate the scene
#   Right-click + drag   -- pan
#   Scroll wheel         -- zoom in / out
#   F1                   -- show all keyboard shortcuts
#   Ctrl+M                -- toggle the "Control" panel (built-in joint sliders)
#
# The notebook sliders below also control the joints in real time.
# Each time a slider moves, update_robot() writes the new angles to data.qpos,
# runs mj_forward(), then calls viewer.sync() to redraw the window.

viewer = mujoco.viewer.launch_passive(model, data)
print("MuJoCo viewer opened -- look for a new window on your desktop.")
print("Use the sliders below, or press Ctrl+M in the viewer for its own controls.")


def update_robot(theta1_deg, theta2_deg):
    """Set joint angles, run FK, and push the updated pose to the viewer."""

    # 1. Write joint angles in radians (MuJoCo always uses radians internally)
    data.qpos[0] = np.radians(theta1_deg)   # joint 1
    data.qpos[1] = np.radians(theta2_deg)   # joint 2

    # 2. Propagate the kinematic chain (fills data.xpos with body positions)
    mujoco.mj_forward(model, data)

    # 3. Push the updated state to the viewer so it redraws the window.
    #    viewer.is_running() returns False if the user has closed the window.
    if viewer.is_running():
        viewer.sync()

    # 4. Print the computed end-effector position below the sliders
    ee_pos = data.xpos[ee_id]   # shape (3,) -- (x, y, z) in world frame
    print(f"theta1={theta1_deg:+6.1f} deg  theta2={theta2_deg:+6.1f} deg"
          f"   ->   EE = ({ee_pos[0]:.4f}, {ee_pos[1]:.4f}) m")


interact(update_robot,
         theta1_deg=FloatSlider(value=45, min=-180, max=180, step=1, description='theta1 (deg)'),
         theta2_deg=FloatSlider(value=60, min=-180, max=180, step=1, description='theta2 (deg)'));

Key Takeaways — Section 3.4

  • An MJCF file describes the robot as a tree of nested <body> elements. Each <joint> inside a body adds one degree of freedom relative to its parent.

  • MjModel holds the static robot structure (loaded once). MjData holds the current state — joint angles in qpos, body positions in xpos, etc.

  • Three-line FK recipe: write angles into data.qpos → call mj_forward(model, data) → read data.xpos[body_id].

  • MuJoCo’s FK gives the same end-effector positions as our geometric and HTM formulas — it is a more general engine that handles any kinematic tree in 2D or 3D without re-deriving formulas.

  • In later chapters we will use this same workflow to simulate the SO-ARM 101 (a real 6-joint robot), loading a CAD-derived MJCF file and calling mj_forward just as we do here.