Skip to content
Physical AI
Chapter 02 30 min read

Understanding Physics Engines

From Newton's laws to numerical integration: how software predicts the next physical state of a robot.

A walking policy is trained on millions of simulated steps before it touches a real floor. Every one of those steps is produced by a physics engine: a program that takes where a robot is now, what its motors are doing and what it is touching, and computes where it will be a few milliseconds later. This chapter builds that program up from Newton's laws. By the end you should be able to read the equation a physics engine solves, predict when a simulation will go unstable, and know what MuJoCo, Gazebo, Isaac Sim and PyBullet actually are.

Every interactive experiment on this page runs a small, purpose-written simulation in your browser. They are numerically integrated with the equations shown next to them, but they are not MuJoCo. Each one says so in its footer. They exist so that you can see one mechanism at a time. MuJoCo itself is covered in Chapter 3.

What a physics engine is

A physics engine is software that predicts how physical objects move under forces. For robotics, the objects are mostly rigid bodies (links, feet, a torso, the floor) connected by joints and pushed by actuators, gravity and contact.

Strip away the details and every physics engine implements one function:

xk+1=step⁡(xk, uk, Δt)x_{k+1} = \operatorname{step}(x_k,\ u_k,\ \Delta t)
  • xkx_k is the state at step kk: every joint angle and velocity, plus the position, orientation and velocity of any free-floating body such as a robot's pelvis.
  • uku_k is the control input: motor torques, or targets that a simulated motor controller turns into torques.
  • Δt\Delta t is the timestep, typically 1 to 5 ms for legged robots.

Call step 200 times and you have one second of simulated robot motion at 200 Hz. Call it four billion times across thousands of parallel copies and you have the experience a reinforcement-learning policy learns from.

Rendering engine versus physics engine

The two are often bundled together (a game engine has both), which is why they get confused. They answer different questions.

Rendering enginePhysics engine
Question it answersWhat does the scene look like from this camera?Where will everything be after Δt\Delta t?
Main inputsMeshes, materials, lights, camera poseMasses, inertias, joints, forces, contact geometry
OutputPixelsNew positions, velocities, contact forces
Typical rate30–120 frames per second, tied to the display200–1000+ steps per second, tied to accuracy and stability
What an error looks likeA wrong colour or shadowA robot that falls through the floor, or a policy that learns to exploit a bug
Needed to train a policy?Only if the policy uses camerasAlways

A simulator can run with no renderer at all. Large-scale locomotion training is usually headless: nobody watches the robots, and skipping rendering saves most of the compute. Conversely, a photorealistic render tells you nothing about whether the masses, friction coefficients or motor limits are right. The geometry used for drawing (a detailed visual mesh) and the geometry used for physics (often simple capsules and boxes) are usually different objects in the same model file.

Why robotics needs a physics engine

Three reasons, in increasing order of importance for learned control:

  1. Design checks. Before building a leg you want to know whether a motor can lift it. That needs dynamics, not drawings.
  2. Safety and cost. A policy that falls 10,000 times while learning would destroy real hardware. In simulation a fall costs a reset.
  3. Data at scale. Reinforcement learning is sample-hungry. A 20-second episode at 200 Hz is 4,000 physics steps. Training typically runs many such episodes in parallel, for hours. Only simulation produces data at that rate.

The catch is that the policy learns the simulator's physics. If the simulated foot grips better than the real one, the policy will rely on that grip. Everything in this chapter is ultimately about understanding what the engine computes, so that you know where it can differ from reality (the sim-to-real gap from Chapter 1).

The physics, from first principles

Newton's laws of motion

Classical mechanics rests on three laws, stated here for a single body:

  1. First law (inertia). A body keeps its velocity, which may be zero, unless a net force acts on it.
  2. Second law. The net force equals mass times acceleration: ∑F=m a\sum F = m\,a. Force and acceleration are vectors and point the same way.
  3. Third law. When body A pushes on body B with force FF, B pushes on A with −F-F. When a foot pushes backward on the ground, the ground pushes the robot forward.

The second law is the one a physics engine evaluates billions of times. Rearranged as a=F/ma = F/m, it tells the engine how quickly velocity must change given the forces it has added up. The third law is why contact forces always come in equal and opposite pairs, and why a robot can only accelerate its body by pushing against something.

Force, mass, acceleration and gravity

Force is measured in newtons (N). One newton accelerates one kilogram at 1 m/s². Mass (kg) measures how strongly a body resists changes in velocity. Acceleration (m/s²) is the rate of change of velocity.

Gravity near the Earth's surface pulls every body down with force m gm\,g, where g≈9.81 m/s2g \approx 9.81\ \text{m/s}^2. Because the force is proportional to mass, the acceleration a=mg/m=ga = mg/m = g is the same for every body. A 0.1 kg ball and a 5 kg ball fall together if air drag is ignored. From rest, height and velocity follow

y(t)=y0−12gt2,v(t)=−gt.y(t) = y_0 - \tfrac12 g t^2, \qquad v(t) = -g t .

A ball dropped from 5 m on Earth lands after 2h/g=1.01\sqrt{2h/g} = 1.01 s at 9.90 m/s. On the Moon (g=1.62g = 1.62) it takes 2.48 s and lands at 4.02 m/s.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Constant acceleration under gravity, the exchange between potential and kinetic energy, and how a coefficient of restitution turns an impact into energy loss.

How it works

The ball is a point mass. Every 1 ms the simulator applies gravity with semi-implicit Euler: velocity first, then position with the new velocity. Before the first bounce the computed height differs from the exact y₀ − ½gt² by exactly ½·g·t·Δt, about 5 mm after one second on Earth.

When the ball passes below the floor, the penetration is removed and the downward velocity is replaced by e times the impact speed, pointing up. This is an impulse-based contact. The readout shows the impulse divided by the step length as an average force. Once the rebound speed drops below 5 cm/s, the ball is treated as resting and the floor supplies exactly m·g.

Adjustable parameters

  • Gravity g (0–25 m/s², presets Moon 1.62, Mars 3.71, Earth 9.81, Jupiter 24.79)
  • Coefficient of restitution e (0–1)
  • Drop height (0.5–20 m)
  • Mass (0.1–5 kg): affects energy and force, not the trajectory

Known limitations

  • No air drag. A real ball in air reaches a terminal velocity.
  • The ball is a point. Spin, deformation and rolling are not modelled.
  • Removing the penetration by clamping the position slightly changes energy at each bounce.

Equations

y¨=−g,y(t)=y0−12gt2\ddot y = -g, \qquad y(t) = y_0 - \tfrac12 g t^2
E=12mv2+mgyE = \tfrac12 m v^2 + m g y
v+=−e v−,hn+1=e2hnv^+ = -e\,v^-, \qquad h_{n+1} = e^2 h_n
vk+1=vk−g Δt,yk+1=yk+vk+1Δtv_{k+1} = v_k - g\,\Delta t, \quad y_{k+1} = y_k + v_{k+1}\Delta t

Core update rule

// lib/sim/ch02-mechanics.ts — stepBall
v -= g * dt;               // semi-implicit Euler
y += v * dt;
if (y < 0) {
  y = 0;                    // remove penetration
  if (v < 0) {
    const vin = -v;
    v = e * vin;            // restitution
    contactForce = m * (1 + e) * vin / dt;
    if (v < REST_SPEED) { v = 0; resting = true; }
  }
}

Explained in Chapter 2: Physics Engines

Things to try:

  • Change the mass. The trajectory does not change, but the energy and the floor force do.
  • Set e = 1. The ball keeps bouncing to the same height, and the total-energy line stays flat. Set e = 0.5 and each bounce reaches 0.52=25%0.5^2 = 25\% of the previous height.
  • Watch the energy chart at each impact. Potential energy turns into kinetic energy on the way down, and the restitution law removes a fraction 1−e21 - e^2 of it at the floor.

The same law, applied to a horizontal push, is the core of every engine. Here a block on a frictionless track receives a 10 N push for 2 s:

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Newton's second law a = F/m, and Newton's first law: when the force stops, the velocity stays constant unless something (here, optional drag) removes it.

How it works

A block slides on a frictionless track. Each 1 ms step computes a = (F − b·v)/m and advances velocity and position with semi-implicit Euler. In the default mode the force acts for 2 s and is then removed, so you can see acceleration drop to zero while velocity stays where it was.

The camera follows the block. Block size scales with the cube root of mass, as it would for a constant-density material.

Adjustable parameters

  • Force mode: 2 s push or constant
  • Applied force F (−20 to 20 N)
  • Mass m (0.5–20 kg)
  • Viscous drag b (0–5 N·s/m)

Known limitations

  • One degree of freedom with no friction. The friction experiment adds Coulomb friction.
  • Drag is linear in velocity. Air drag at everyday speeds is closer to quadratic.

Equations

mx¨=F−bx˙m\ddot x = F - b\dot x
x(t)=12Fmt2(b=0, from rest)x(t) = \tfrac12 \tfrac{F}{m} t^2 \quad (b = 0,\ \text{from rest})
v∞=F/b(b>0)v_\infty = F / b \quad (b > 0)

Core update rule

applied = t < pushDuration ? F : 0;
a = (applied - b * v) / m;   // Newton's second law
v += a * dt;
x += v * dt;

Explained in Chapter 2: Physics Engines

With the defaults (10 N, 2 kg) the acceleration is 5 m/s². After 2 s the block moves at 10 m/s and has travelled 10 m. Then the force stops, the acceleration drops to zero, and the velocity stays at 10 m/s. That is the first law: nothing is needed to keep something moving, only to change its motion. Add drag and the block slows down. Under a constant force it levels off at v∞=F/bv_\infty = F/b.

Inertia

Inertia is resistance to changes in motion. For straight-line motion it is just mass. For rotation it is the moment of inertia II (kg·m²), which depends on how the mass is distributed about the rotation axis:

I=∑imiri2.I = \sum_i m_i r_i^2 .

Mass far from the axis counts much more than mass close to it, because of the r2r^2. A uniform rod of mass mm and length LL has I=112mL2I = \tfrac{1}{12} m L^2 about its centre but I=13mL2I = \tfrac13 m L^2 about one end, four times more. This is why legged robots put their heavy motors near the hip. A light lower leg can be swung quickly with a modest motor.

A rigid body in 3D has a 3×3 inertia tensor rather than a single number, because its resistance to rotation differs per axis. Robot description files store it as six numbers (the tensor is symmetric) together with the body's mass and centre-of-mass position. These ten numbers per link are the inertial parameters that system identification tries to measure.

Torque and angular motion

A force applied off-centre makes a body rotate. Its turning effect is the torque

τ=r×F,∣τ∣=r Fsin⁡φ,\tau = r \times F, \qquad |\tau| = r\,F\sin\varphi ,

measured in newton-metres (N·m). The rotational form of Newton's second law is

∑τ=I α,\sum \tau = I\,\alpha ,

where α\alpha is angular acceleration (rad/s²). Angular velocity ω\omega (rad/s) and angle θ\theta (rad) relate to it the same way velocity and position relate to linear acceleration.

Gravity creates a torque on any link whose centre of mass is not directly above or below its joint. For a link of mass mm with its centre of mass at distance ll from the joint, at angle θ\theta from hanging straight down:

τg=−mglsin⁡θ.\tau_g = -m g l \sin\theta .

At θ=90°\theta = 90° (horizontal) the torque is largest. A 1 kg, 0.5 m uniform link (l=0.25l = 0.25 m) needs 1×9.81×0.25=2.451 \times 9.81 \times 0.25 = 2.45 N·m just to hold still there. An electric motor can supply torque only up to its limit. If that limit is below 2.45 N·m, no controller can hold the link horizontal.

Kinematics versus dynamics

These two words divide mechanics into two questions:

  • Kinematics is geometry and motion without forces. Given the joint angles, where is the foot? Given joint velocities, how fast is the foot moving? Forward kinematics maps joint angles to body positions. Inverse kinematics goes the other way.
  • Dynamics connects motion to its causes. Forward dynamics answers: given the state and the applied torques, what are the accelerations? Inverse dynamics answers: what torques are needed to produce a desired acceleration?

A physics engine runs both every step. It runs kinematics to find where every body and collision shape is, and forward dynamics to find out how the bodies accelerate. A controller that computes "the torque needed to hold this pose" is doing inverse dynamics. The holding torque in the arm experiment below is a one-joint example.

Rigid body dynamics

A rigid body is an idealised object that never deforms: the distance between any two of its points stays fixed. Real links bend slightly, but treating them as rigid makes the problem tractable and is accurate enough for most robot links.

A free rigid body in 3D needs six numbers to describe its position (three for location, three for orientation) and six for its velocity. Its motion obeys the Newton–Euler equations: F=m v˙cF = m\,\dot v_c for the centre of mass and τ=Iω˙+ω×Iω\tau = I\dot\omega + \omega \times I\omega for rotation. The extra term ω×Iω\omega \times I\omega is why a spinning object can wobble even with no torque applied.

A robot is many rigid bodies linked by joints. Rather than tracking six numbers per body and then forcing them to stay connected, most robotics engines describe the robot by its generalised coordinates qq: the free-floating base pose plus one coordinate per joint degree of freedom. In these coordinates the whole robot obeys one matrix equation:

M(q) q¨+C(q,q˙)=τ+J⊤fM(q)\,\ddot q + C(q, \dot q) = \tau + J^\top f
SymbolMeaningSize for a robot with nvn_v velocity DoF
q, q˙, q¨q,\ \dot q,\ \ddot qpositions, velocities, accelerations in generalised coordinatesnvn_v (positions can be longer, see below)
M(q)M(q)mass matrix: the inertia "felt" by each coordinate, including coupling between jointsnv×nvn_v \times n_v, symmetric, positive definite
C(q,q˙)C(q, \dot q)bias forces: gravity, Coriolis and centrifugal effectsnvn_v
τ\tauactuator torques and other applied generalised forces (springs, joint damping)nvn_v
JJcontact Jacobian: maps q˙\dot q to the velocity of each contact point3nc×nv3n_c \times n_v for ncn_c point contacts
ffcontact and constraint forces (normal force and friction at each contact)3nc3n_c

J⊤fJ^\top f converts forces at the feet into their effect on every joint. If the contact forces ff were known, forward dynamics would just be q¨=M−1(τ+J⊤f−C)\ddot q = M^{-1}(\tau + J^\top f - C). The hard part is that ff is not known in advance. It depends on the motion, and the motion depends on it. Finding ff is the job of the contact solver, discussed below.

Computing MM, CC and their combinations efficiently is a solved problem. Featherstone's recursive algorithms (the Recursive Newton–Euler Algorithm for inverse dynamics and the Articulated-Body Algorithm for forward dynamics) do it in time proportional to the number of bodies. They are the basis of many robotics engines.

Degrees of freedom

The degrees of freedom (DoF) of a system are the number of independent ways it can move. A hinge has one, a ball joint three, and a free body six.

A legged robot is a floating-base system. Its pelvis is not bolted to anything, so the model includes a 6-DoF free joint between the world and the pelvis, plus the joints of the legs. Engines often store orientation as a unit quaternion (four numbers) rather than three angles, to avoid singularities. As a result, the position vector is one element longer than the velocity vector. In MuJoCo's naming these lengths are nq and nv.

Asimov is a legs-only platform with 12 actuated leg joints and 2 passive toe joints. Its ankles use a parallel mechanism rather than a directly driven serial ankle, and the simulator maps ankle pitch and roll through that mechanism.

Illustrative example

If each of those 14 joints were a single hinge, and the parallel ankle linkage were reduced to its pitch and roll joints, the model would have nv=6+14=20n_v = 6 + 14 = 20 velocity DoF and nq=7+14=21n_q = 7 + 14 = 21 position coordinates. Menlo's pages do not describe how the linkage is represented in the model file, so treat these numbers as arithmetic, not as a documented fact.

Notice that DoF and actuators are different counts. The free base has six DoF and no actuator, and the passive toes have DoF but no motor. Such a system is underactuated: the robot cannot command its pelvis directly. It can only move it by pushing on the ground. This is the fundamental reason walking is hard.

Joints and actuators

A joint is a kinematic restriction between two bodies that leaves certain motions free:

JointFree motionDoFRobot example
Hinge (revolute)rotation about one axis1knee, hip pitch
Slide (prismatic)translation along one axis1linear actuator, gantry
Ball (spherical)any rotation3shoulder approximated as one joint
Freeany translation and rotation6floating base of a legged robot
Fixed (weld)none0rigidly mounted sensor or battery

An actuator produces force or torque on a joint. In simulation it is a model with its own parameters. The simplest is an ideal motor that applies the commanded torque. More realistic models add a torque limit (saturation), a transmission ratio (gear), rotor inertia reflected through the gear (often called armature), joint friction, and delay between command and effect. Many legged robots, including policy-driven ones, command position targets, and a low-level PD loop converts them to torque:

τ=clip⁡ ⁣(Kp (q∗−q)−Kd q˙, −τmax, τmax).\tau = \operatorname{clip}\!\big(K_p\,(q^* - q) - K_d\,\dot q,\ -\tau_{max},\ \tau_{max}\big).

Menlo's Asimov simulation models actuator saturation, friction and delay. The pages do not publish the numbers.

The experiment below is a single link driven by such a motor. It is the smallest system that contains inertia, gravity torque, damping, a controller and a saturating actuator. Chapter 3 revisits the same arm as a MuJoCo model, with its mjData arrays and the MJCF that describes it.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Rotational Newton's law I·α = Σ τ for a robot link. Gravity torque depends on angle, a motor has a torque limit, and a PD position controller droops under load or fails outright when the motor is too weak.

How it works

The link is a uniform rod pivoting at one end, so I = m L²/3 and its centre of mass sits at L/2. Gravity produces τ_g = −m g (L/2) sin θ, with θ measured from hanging straight down. Joint friction is viscous, −b·ω.

In direct-torque mode you set the motor torque. In PD mode the motor is asked for τ = Kp(θ* − θ) − Kd·ω, the same structure as the low-level joint controllers on legged robots. Either command is clipped to ±τ_max before it reaches the link, then α is integrated with semi-implicit Euler at 1 kHz.

Adjustable parameters

  • Command mode: PD position or direct torque
  • Torque command (−8 to 8 N·m)
  • Target angle (−180° to 180°), Kp (0–60 N·m/rad), Kd (0–3 N·m·s/rad)
  • Motor torque limit (0.5–10 N·m)
  • Link mass (0.3–3 kg), length (0.25–1 m)
  • Joint friction b (0–0.5 N·m·s/rad)

Known limitations

  • The motor is ideal below its limit: no delay, no speed-dependent torque drop, no gear backlash or rotor inertia (armature).
  • One joint. Multi-link arms add Coriolis and coupling terms, C(q, q̇) in the chapter's equation.

Equations

Iθ¨=τm−mgL2sin⁡θ−bθ˙,I=13mL2I\ddot\theta = \tau_{m} - m g \tfrac{L}{2}\sin\theta - b\dot\theta, \qquad I = \tfrac13 m L^2
τm=clip⁡(Kp(θ∗−θ)−Kdθ˙, −τmax, τmax)\tau_{m} = \operatorname{clip}\big(K_p(\theta^* - \theta) - K_d\dot\theta,\ -\tau_{max},\ \tau_{max}\big)
static droop: Kp(θ∗−θ)=mgL2sin⁡θ\text{static droop: } K_p(\theta^* - \theta) = m g \tfrac{L}{2}\sin\theta

Core update rule

tauReq   = mode === "torque" ? tauCmd : kp * (target - theta) - kd * omega;
tauMotor = clamp(tauReq, -tauMax, tauMax);
tauGrav  = -m * g * (L / 2) * Math.sin(theta);
alpha    = (tauMotor + tauGrav - b * omega) / (m * L * L / 3);
omega   += alpha * dt;
theta   += omega * dt;

Explained in Chapter 2: Physics Engines

Things to try:

  • In PD mode with the defaults, target 90°. The arm settles about 7° short of the target. The PD law only produces torque from error, so it needs an error of ≈2.45/20=0.12\approx 2.45 / 20 = 0.12 rad to generate the 2.45 N·m that gravity demands. Raise KpK_p and the droop shrinks.
  • Lower the torque limit below 2.45 N·m. The arm cannot reach horizontal at any gain, and the motor-state readout shows SATURATED.
  • Set KdK_d to zero and the joint friction to zero. The arm overshoots and rings, because nothing removes energy.
  • Double the link length. Inertia grows four times (L2L^2) and gravity torque doubles. The motor has to work much harder.

Constraints

A constraint is any rule that restricts how bodies may move. Joints are constraints ("these two bodies share a hinge axis"). So are joint limits ("the knee cannot bend backward"), closed kinematic loops such as a parallel ankle linkage, and contact ("the foot may not pass through the floor").

There are two broad ways to enforce constraints:

  • Reduced coordinates. Choose coordinates that cannot violate the constraint. A hinge described by one angle simply has no way to come apart. This is the generalised-coordinate approach above, used by MuJoCo, DART and Featherstone-style solvers.
  • Constraint forces. Describe each body with full maximal coordinates and compute the forces needed to hold the joint together. This is how ODE and many game engines work. It is flexible, but small errors let joints drift apart, so the solver has to correct them continuously.

Even reduced-coordinate engines need constraint forces for things that are not tree-structured joints: contacts, joint limits, closed loops and equality constraints. Mathematically, every constraint contributes rows to the Jacobian JJ and unknowns to ff in the equation of motion.

Friction

Friction is the tangential force at a contact that resists sliding. The standard engineering model, Coulomb friction, has two regimes:

  • Static (sticking). While the surfaces are not sliding, friction takes whatever value is needed to prevent sliding, up to a limit: ∣ft∣≤μsN|f_t| \le \mu_s N.
  • Kinetic (sliding). Once sliding, friction has magnitude μkN\mu_k N and opposes the sliding velocity. Usually μk≤μs\mu_k \le \mu_s.

Here NN is the normal force pressing the surfaces together, and the coefficients μ\mu are dimensionless properties of the material pair. Rubber on concrete is around 0.6 to 0.8 or higher, steel on ice is a few hundredths. In 3D the set of allowed contact forces forms a friction cone: the force can point anywhere within an angle arctan⁡μ\arctan\mu of the surface normal. Many engines approximate the cone with a pyramid of a few faces to make the solver simpler.

The first sentence of the static regime is the one people get wrong: static friction is not a constant force. Push lightly and friction pushes back lightly. Push harder and friction matches you, until it cannot.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Friction is not a fixed force. At rest it takes whatever value is needed to prevent motion, up to μs·N. Once the block slides, friction drops to μk·N and opposes the velocity.

How it works

The block sits on an incline. The normal force is N = m·g·cos θ and gravity pulls along the slope with m·g·sin θ. While the block is stuck, the simulator checks whether the sum of the applied force and the gravity component exceeds μs·N. If not, friction exactly cancels them and nothing moves.

When the limit is exceeded the block breaks loose. Friction then becomes −μk·N·sign(v), and Newton's second law is integrated. If the velocity crosses zero inside a step, the block is stopped and the static check runs again. In ramp mode the applied force grows at 2 N/s, which shows the classic picture: friction rises with the push, peaks at μs·N, then drops to μk·N.

Adjustable parameters

  • Applied force: ramp at 2 N/s, or manual (−60 to 60 N)
  • Incline angle θ (0–45°)
  • Mass m (0.5–10 kg)
  • Static coefficient μs (0.05–1.2)
  • Kinetic coefficient μk (0 to μs)

Known limitations

  • Coulomb friction is an empirical model. Real friction also depends on velocity (the Stribeck effect), temperature, wear and contact time.
  • When the block reaches the end of the slope it is simply stopped. The end-stop reaction force is not shown.
  • Physics engines usually approximate the friction cone and soften the stick–slip switch. This explicit switch is a teaching model.

Equations

N=mgcos⁡θ,Fext=P−mgsin⁡θN = m g \cos\theta, \qquad F_{ext} = P - m g \sin\theta
stuck if ∣Fext∣≤μsN  ⇒  f=−Fext\text{stuck if } |F_{ext}| \le \mu_s N \;\Rightarrow\; f = -F_{ext}
sliding: f=−μkN sign⁡(x˙),mx¨=Fext+f\text{sliding: } f = -\mu_k N\,\operatorname{sign}(\dot x), \quad m\ddot x = F_{ext} + f
θslip=arctan⁡μs\theta_{slip} = \arctan \mu_s

Core update rule

if (stuck) {
  if (Math.abs(fext) <= muS * N) { friction = -fext; a = 0; return; }
  stuck = false;                      // breakaway
}
const dir = v !== 0 ? Math.sign(v) : Math.sign(fext);
friction = -dir * muK * N;
a = (fext + friction) / m;
const vNew = v + a * dt;
if (v !== 0 && Math.sign(vNew) !== Math.sign(v)) { v = 0; stuck = true; }
else v = vNew;
x += v * dt;

Explained in Chapter 2: Physics Engines

With the defaults (2 kg on flat ground, μs=0.6\mu_s = 0.6, μk=0.4\mu_k = 0.4), the normal force is 19.62 N. In ramp mode the applied force grows at 2 N/s. Friction tracks it exactly until it reaches μsN=11.77\mu_s N = 11.77 N, at about 5.9 s. The block then breaks loose and friction drops to μkN=7.85\mu_k N = 7.85 N, so the net force jumps to about 3.9 N and the block accelerates at roughly 2 m/s². That sudden drop is stick–slip. It is why a heavy box lurches when it finally moves.

Now set the push to manual zero and raise the incline angle. The block stays put until tan⁡θ>μs\tan\theta > \mu_s, at θ=arctan⁡0.6≈31°\theta = \arctan 0.6 \approx 31°. For a walking robot, the equivalent question is whether the ratio of tangential to normal foot force stays inside the friction cone. If it leaves the cone, the foot slips.

Collision detection

Before an engine can compute contact forces it has to know which bodies touch, where, and how deeply they overlap. This is collision detection, and it is usually split into two phases:

  1. Broad phase. A cheap test that rules out pairs that are far apart, typically by comparing axis-aligned bounding boxes. With 30 collision shapes there are 435 possible pairs. The broad phase reduces that to the handful that might touch.
  2. Narrow phase. An exact geometric test on the remaining pairs. It produces contact points, each with a position, a normal direction, and a penetration depth (or separation distance).

The narrow phase is fast and robust for simple primitives (spheres, capsules, boxes, planes) and much slower and less predictable for arbitrary triangle meshes. Engines often accept only convex meshes for collision, and require non-convex shapes to be split into convex pieces. A sphere against a plane has a closed-form answer. Two general meshes need iterative algorithms such as GJK and EPA, which are more expensive and can produce contact points that jump from step to step.

Asimov's simulation uses capsule-based foot and toe geometry with explicit foot and toe contact points and tuned contact parameters. Menlo prefers explicit primitives over detailed mesh collision because they give more conservative, repeatable contact.

This choice is common for learned locomotion. A capsule's contact with a flat floor is cheap, smooth and the same every time. A policy trained against it does not learn to exploit odd contact points produced by a detailed mesh.

Contact forces

Once collision detection has listed the contacts, the engine must compute the contact force ff at each one. Physically, rigid contact satisfies three conditions:

  • The bodies do not interpenetrate (gap ≥0\ge 0).
  • The normal force only pushes, never pulls (fn≥0f_n \ge 0).
  • Force acts only when touching: gap×fn=0\text{gap} \times f_n = 0. Either there is a gap and no force, or there is contact and some force.

Together these are a complementarity condition. Combined with the friction cone, they make contact the hardest part of robot simulation. Forces switch on and off abruptly, and many contacts must be solved together because they interact (both feet on the ground share the robot's weight). There are three main approaches:

ApproachIdeaStrengthsWeaknesses
Penalty (soft) contactAllow a small overlap δ\delta and push back with a spring–damper fn=kδ+cδ˙f_n = k\delta + c\dot\deltaSimple, smooth, easy to differentiateStiff springs need tiny timesteps. Soft springs let objects sink and bounce
Impulse / velocity-level (hard) contactChange velocities instantaneously so contacts stop approaching, then correct any overlapStable with larger timesteps, no visible sinkingCollisions are instantaneous, so forces are only known as impulses. Many simultaneous contacts need iterative solvers
Constraint optimisation (LCP, convex)Solve for all contact forces at once as a complementarity or optimisation problemHandles many coupled contacts with frictionExpensive, and the exact formulation varies between engines

MuJoCo uses a variant of the third approach with deliberately soft constraints: it solves a convex optimisation for all contact forces at once, with parameters that set how stiff and how damped each contact is. The softness keeps the problem well-behaved and smooth, at the price of allowing small, controlled penetration. Chapter 3 explains its solref and solimp parameters.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

Two ways a simulator can stop objects passing through each other: a stiff spring–damper that allows small penetration (penalty, soft contact), or an instantaneous velocity change plus position correction (impulse, hard contact). Also shows why stiff contact needs small timesteps.

How it works

Two frictionless discs move under gravity inside a box. Every step the simulator checks circle–floor, circle–wall and circle–circle overlap (narrow-phase collision detection; with two bodies no broad phase is needed).

Penalty model: an overlap δ produces a normal force F = max(0, k·δ + c·δ'), with c = 2ζ√(k·m_eff). The force is added like any other force and integrated with semi-implicit Euler. A resting disc sinks to δ = m·g/k. If ω·Δt = √(k/m)·Δt exceeds about 2, the explicit integration of the contact spring becomes unstable and the simulation diverges.

Impulse model: bodies are integrated freely, then any overlap is removed by moving the bodies apart (split by inverse mass), and the approaching normal velocity is reversed and scaled by e. The applied impulse divided by Δt is reported as an average force. Four sequential passes let simultaneous contacts settle.

Adjustable parameters

  • Contact model: penalty or impulse
  • Stiffness k (10^2.5–10^6 N/m), damping ratio ζ (0–1) — penalty
  • Restitution e (0–1) — impulse
  • Physics rate (250 Hz, 1 kHz, 4 kHz)
  • Mass of the large disc (0.2–5 kg)

Known limitations

  • Frictionless contact. The discs slide and never spin. Real engines add tangential friction and rolling.
  • The impulse model resolves contacts one at a time. Engines such as MuJoCo instead solve all contacts together as an optimisation problem.
  • Discs only. Real collision detection handles boxes, capsules and meshes, and uses a broad phase to avoid testing every pair.

Equations

δ=ra+rb−∥pb−pa∥,n=pb−pa∥pb−pa∥\delta = r_a + r_b - \lVert p_b - p_a \rVert, \qquad n = \frac{p_b - p_a}{\lVert p_b - p_a \rVert}
Fn=max⁡(0, k δ+c δ˙),c=2ζk meffF_n = \max\big(0,\ k\,\delta + c\,\dot\delta\big), \quad c = 2\zeta\sqrt{k\,m_{eff}}
j=−(1+e) (vb−va)⋅n1/ma+1/mb,va−=jman, vb+=jmbnj = \frac{-(1+e)\,(v_b - v_a)\cdot n}{1/m_a + 1/m_b}, \qquad v_a \mathrel{-}= \frac{j}{m_a} n,\ v_b \mathrel{+}= \frac{j}{m_b} n
penalty stability (undamped, semi-implicit Euler): k/meff  Δt<2\text{penalty stability (undamped, semi-implicit Euler): } \sqrt{k/m_{eff}}\;\Delta t < 2

Core update rule

// Penalty (soft): a force from the overlap
const depth = a.r + b.r - dist;
if (depth > 0) {
  const vn = dot(sub(b.v, a.v), n);            // separating speed
  const F = Math.max(0, k * depth + c * -vn);  // spring + damper, never pulls
  fA -= F * n;  fB += F * n;
}

// Impulse (hard): fix positions, then velocities
if (depth > 0) {
  a.p -= n * depth * wa / (wa + wb);  b.p += n * depth * wb / (wa + wb);
  const vn = dot(sub(b.v, a.v), n);
  if (vn < 0) {
    const j = -(1 + e) * vn / (wa + wb);
    a.v -= j * wa * n;  b.v += j * wb * n;
  }
}

Explained in Chapter 2: Physics Engines

Things to try:

  • In penalty mode, drag the stiffness down to 102.510^{2.5} N/m. The discs sink visibly into the floor. A resting disc settles at δ=mg/k\delta = mg/k, which is 31 mm for the 1 kg disc. At the default 104.510^{4.5} N/m it is 0.31 mm.
  • Set ζ=0\zeta = 0. The contact becomes a perfect spring and the discs keep bouncing. Raise ζ\zeta towards 1 and impacts are absorbed.
  • Push stiffness to 10610^6 N/m and select 250 Hz. The simulation diverges within moments. The stability readout ω·Δt passes 2. Switch to 4 kHz and the same contact is stable. Stiff contact forces small timesteps is the single most important practical rule of contact simulation.
  • Switch to impulse mode. Penetration stays near zero, and the force chart shows tall, one-step spikes, because the whole collision happens inside a single step.

How a physics engine calculates the next state

Everything above comes together in one loop that runs once per timestep:

  1. 1Current stateq, q̇, time t
  2. 2Kinematics + collision detectionbody poses, contact points, normals, depths
  3. 3Smooth forcesgravity, Coriolis C(q,q̇), actuator τ, springs, damping
  4. 4Constraint & contact solvefind f: no penetration, friction cone, joint limits
  5. 5Integrateq̈ → q̇ → q, advance t by Δt

Loops back: Integrate → Current state

One physics step. The new state becomes the input to the next step. A policy reads observations from the state every few steps and writes new actuator commands.

In equations, for one step of length Δt\Delta t:

1. kinematics:body poses, contacts, J(q) from q2. smooth dynamics:M(q), C(q,q˙), τ=τact(u,q,q˙)+τpassive(q,q˙)3. constraint solve:find f such that Mq¨=τ−C+J⊤f respects contact, friction and limits4. integrate:q˙k+1=q˙k+Δt q¨,qk+1=qk⊕Δt q˙k+1\begin{aligned} &\text{1. kinematics:} && \text{body poses, contacts, } J(q) \text{ from } q \\ &\text{2. smooth dynamics:} && M(q),\ C(q,\dot q),\ \tau = \tau_{act}(u, q, \dot q) + \tau_{passive}(q, \dot q) \\ &\text{3. constraint solve:} && \text{find } f \text{ such that } M\ddot q = \tau - C + J^\top f \text{ respects contact, friction and limits} \\ &\text{4. integrate:} && \dot q_{k+1} = \dot q_k + \Delta t\,\ddot q, \qquad q_{k+1} = q_k \oplus \Delta t\,\dot q_{k+1} \end{aligned}

The ⊕\oplus reminds you that orientations stored as quaternions cannot simply be added. They are updated by integrating angular velocity on the rotation group.

A worked step

Take the single-joint arm from the experiment: m=1m = 1 kg, L=0.5L = 0.5 m, so I=mL2/3=0.0833I = mL^2/3 = 0.0833 kg·m². The arm is horizontal (θ=90°\theta = 90°), momentarily still (ω=0\omega = 0), and the motor applies τm=1.0\tau_m = 1.0 N·m. The timestep is 2 ms. There are no contacts.

  1. State: θk=1.5708\theta_k = 1.5708 rad, ωk=0\omega_k = 0.
  2. Kinematics: the centre of mass is 0.25 m out, horizontally.
  3. Forces: gravity torque =−1×9.81×0.25×sin⁡90°=−2.4525= -1 \times 9.81 \times 0.25 \times \sin 90° = -2.4525 N·m. Damping =0= 0. Net torque =1.0−2.4525=−1.4525= 1.0 - 2.4525 = -1.4525 N·m.
  4. Dynamics: α=−1.4525/0.0833=−17.43\alpha = -1.4525 / 0.0833 = -17.43 rad/s².
  5. Integrate (semi-implicit Euler): ωk+1=0+0.002×(−17.43)=−0.0349\omega_{k+1} = 0 + 0.002 \times (-17.43) = -0.0349 rad/s, then θk+1=1.5708+0.002×(−0.0349)=1.57073\theta_{k+1} = 1.5708 + 0.002 \times (-0.0349) = 1.57073 rad.

The arm has started to fall. A full robot simulator does exactly this, but with matrices instead of scalars, dozens of joints, and a contact solve in the middle.

Numerical integration

The equation of motion gives accelerations. To get positions, the engine must integrate twice over time. Computers cannot integrate continuously, so they take finite steps. The rule used to take a step is the integrator, and it matters far more than its simplicity suggests.

Writing the system as x˙=v\dot x = v, v˙=a(x,v)\dot v = a(x, v):

  • Explicit (forward) Euler uses the values at the start of the step for both updates: xk+1=xk+Δt vkx_{k+1} = x_k + \Delta t\,v_k, vk+1=vk+Δt akv_{k+1} = v_k + \Delta t\,a_k. It is simple, first-order accurate, and systematically adds energy to oscillating systems.
  • Semi-implicit (symplectic) Euler updates velocity first, then position using the new velocity: vk+1=vk+Δt akv_{k+1} = v_k + \Delta t\,a_k, xk+1=xk+Δt vk+1x_{k+1} = x_k + \Delta t\,v_{k+1}. It has the same cost and the same first-order accuracy, but it is symplectic: for conservative systems its energy error stays bounded instead of growing. Many game and robotics engines use it or a variant. MuJoCo's default integrator is semi-implicit Euler, with an option to treat joint damping implicitly.
  • Runge–Kutta 4 (RK4) evaluates the dynamics four times per step at intermediate points and combines them. It is fourth-order accurate: halve Δt\Delta t and the error falls by about 16×. It costs four dynamics evaluations per step and is not symplectic, so over very long runs its energy slowly drifts. MuJoCo offers it as an option.
  • Implicit methods evaluate forces at the end of the step, which requires solving an equation. They are much more stable for stiff systems such as stiff springs, heavy damping and contact. MuJoCo's implicit and implicitfast integrators treat velocity-dependent forces this way.

"First-order" and "fourth-order" describe how the error per unit time shrinks with the timestep: proportionally to Δt\Delta t for Euler, to Δt4\Delta t^4 for RK4.

Before comparing integrators, here is a system where we know the right answer. A pendulum's small-angle period is T0=2πL/gT_0 = 2\pi\sqrt{L/g}, which is 2.006 s for L=1L = 1 m. That formula assumes sin⁡θ≈θ\sin\theta \approx \theta. The experiment integrates the full nonlinear equation with RK4 and shows the small-angle solution as a ghost.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

The small-angle formula T = 2π√(L/g) is an approximation. At large amplitudes the true pendulum is slower, and an accurate integrator conserves energy when there is no damping.

How it works

The nonlinear equation θ'' = −(g/L) sin θ − c·θ' is integrated with fourth-order Runge–Kutta at 1 kHz. The ghost pendulum is the closed-form solution of the linearised equation (sin θ ≈ θ), including the same damping.

The measured period comes from successive upward zero crossings, interpolated within a step. It is compared with 2π√(L/g) and with the exact undamped period 4√(L/g)·K(sin(θ₀/2)), where K is the complete elliptic integral of the first kind, computed with the arithmetic–geometric mean.

Adjustable parameters

  • Release angle θ₀ (5–175°)
  • Length L (0.25–3 m)
  • Damping c (0–1 s⁻¹)
  • Show/hide small-angle model

Known limitations

  • Point mass on a massless rod. A real pendulum has a distributed mass and pivot friction that is not purely viscous.
  • The rod is drawn at a fixed size regardless of L.

Equations

θ¨=−gLsin⁡θ−c θ˙\ddot\theta = -\tfrac{g}{L}\sin\theta - c\,\dot\theta
θlin(t)=θ0e−ζω0t(cos⁡ωdt+ζω0ωdsin⁡ωdt),ω0=g/L, ζ=c2ω0\theta_{lin}(t) = \theta_0 e^{-\zeta\omega_0 t}\Big(\cos\omega_d t + \tfrac{\zeta\omega_0}{\omega_d}\sin\omega_d t\Big), \quad \omega_0 = \sqrt{g/L},\ \zeta = \tfrac{c}{2\omega_0}
T0=2πL/g,T=4L/g  K ⁣(sin⁡θ02)T_0 = 2\pi\sqrt{L/g}, \qquad T = 4\sqrt{L/g}\;K\!\big(\sin\tfrac{\theta_0}{2}\big)
E=12mL2θ˙2+mgL(1−cos⁡θ)E = \tfrac12 m L^2 \dot\theta^2 + m g L (1 - \cos\theta)

Core update rule

const f = (th: number, om: number) => -(g / L) * Math.sin(th) - c * om;
// one RK4 step
const k1 = [om, f(th, om)];
const k2 = [om + h/2 * k1[1], f(th + h/2 * k1[0], om + h/2 * k1[1])];
const k3 = [om + h/2 * k2[1], f(th + h/2 * k2[0], om + h/2 * k2[1])];
const k4 = [om + h   * k3[1], f(th + h   * k3[0], om + h   * k3[1])];
th += h/6 * (k1[0] + 2*k2[0] + 2*k3[0] + k4[0]);
om += h/6 * (k1[1] + 2*k2[1] + 2*k3[1] + k4[1]);

Explained in Chapter 2: Physics Engines

Released at 10°, the two pendulums stay together for many swings. Released at 90°, the true period is 1.180×T0=2.3681.180 \times T_0 = 2.368 s, and the ghost visibly runs ahead within a couple of swings. With damping off, the energy readout stays at 100.0% to the displayed precision. That is RK4 at 1 kHz conserving energy as the real system does. This is a reminder that "the physics" in an engine is a model: the linearised pendulum is also physics, just a cruder model.

Simulation timesteps

Now hold the system fixed and change only the integrator and the timestep. This is the most important experiment in the chapter.

Loading simulation…
▸How this works · equations · source · limitationsOpen in lab

What it demonstrates

The same equations give different answers depending on the integrator and timestep. Explicit Euler steadily adds energy to an oscillator, semi-implicit Euler keeps energy bounded, and RK4 is far more accurate per step. Every method fails if the timestep is too large.

How it works

Three copies of one system (a 1 kg spring–mass, or a 1 m pendulum) start from the same state and are advanced with the same Δt by explicit Euler, semi-implicit Euler and classic RK4. The spring–mass reference is its exact solution x₀·cos ωt. The pendulum has no elementary closed form, so its reference is RK4 with sub-steps of at most 0.5 ms.

The phase portrait plots position against velocity. Energy conservation makes the exact trajectory a closed loop. For the spring, explicit Euler multiplies the energy by exactly (1 + ω²Δt²) every step. Semi-implicit Euler stays on a slightly distorted closed loop while ω·Δt < 2. RK4 slowly loses energy, but at a rate that is negligible for small ω·Δt.

Playback speed changes how many simulated seconds run per wall-clock second. It does not change the physics, which shows that simulation frequency and real-time execution are separate things.

Adjustable parameters

  • System: spring–mass or pendulum
  • Timestep Δt (0.001–0.3 s)
  • Spring stiffness k (1–50 N/m)
  • Pendulum release angle θ₀ (10–170°)
  • Playback speed (0.25×, 1×, 4×)

Known limitations

  • One degree of freedom. In a full robot, the stiffest element (often contact or a stiff joint) sets the largest stable timestep.
  • Real engines also use implicit or partially implicit integrators, for example MuJoCo's implicit-in-velocity options, which this experiment does not show.

Equations

explicit Euler: xk+1=xk+Δt vk,vk+1=vk+Δt a(xk)\text{explicit Euler: } x_{k+1} = x_k + \Delta t\,v_k,\quad v_{k+1} = v_k + \Delta t\,a(x_k)
semi-implicit: vk+1=vk+Δt a(xk),xk+1=xk+Δt vk+1\text{semi-implicit: } v_{k+1} = v_k + \Delta t\,a(x_k),\quad x_{k+1} = x_k + \Delta t\,v_{k+1}
RK4: yk+1=yk+Δt6(k1+2k2+2k3+k4)\text{RK4: } y_{k+1} = y_k + \tfrac{\Delta t}{6}(k_1 + 2k_2 + 2k_3 + k_4)
Ek+1Euler=(1+ω2Δt2) Ekfor x¨=−ω2xE_{k+1}^{\text{Euler}} = (1 + \omega^2\Delta t^2)\,E_k \quad \text{for } \ddot x = -\omega^2 x

Core update rule

// lib/sim/ch02-integrators.ts
export function eulerStep(s, t, dt, a) {
  const acc = a(s.x, s.v, t);
  return { x: s.x + s.v * dt, v: s.v + acc * dt };
}
export function semiImplicitStep(s, t, dt, a) {
  const v = s.v + a(s.x, s.v, t) * dt;   // velocity first
  return { x: s.x + v * dt, v };          // then position with the new velocity
}

Explained in Chapter 2: Physics Engines

With the spring–mass defaults (k=10k = 10 N/m, m=1m = 1 kg, so ω=3.16\omega = 3.16 rad/s, and Δt=50\Delta t = 50 ms, so ωΔt=0.16\omega\Delta t = 0.16):

  • Explicit Euler spirals outward in the phase portrait. For this system its energy grows by exactly (1+ω2Δt2)(1 + \omega^2\Delta t^2) every step. That is only 2.5% per step here, but it compounds: after 10 s (200 steps) the energy is about 140 times its starting value. No physical system does this. The integrator is inventing energy.
  • Semi-implicit Euler stays on a closed, slightly tilted loop. Its energy oscillates by up to about 8% at this step size, but it does not drift. It goes unstable only when ωΔt>2\omega\Delta t > 2. Try k=50k = 50 N/m and Δt=0.3\Delta t = 0.3 s.
  • RK4 is almost indistinguishable from the exact solution. Its position error after 10 s is about 2×10−42 \times 10^{-4} m at this step size, and halving Δt\Delta t cuts it roughly sixteenfold.

Two rules follow, and both apply directly to robot simulation:

  1. The timestep must be small compared with the fastest motion in the system. The relevant quantity is ωΔt\omega\Delta t, where ω\omega is the highest natural frequency present. In a robot, the stiffest element is usually contact or a stiff position controller, not the visible swinging of a leg. A contact with stiffness 10510^5 N/m on 1 kg has ω=316\omega = 316 rad/s. Semi-implicit Euler is stable only if Δt<2/316=6.3\Delta t < 2/316 = 6.3 ms, and it is accurate only well below that.
  2. Stable is not the same as accurate. Semi-implicit Euler at ωΔt=1.5\omega\Delta t = 1.5 does not blow up, but its trajectory is noticeably wrong. A policy trained on that trajectory learns the wrong physics without any warning.

This is why legged-robot simulators run physics at hundreds of hertz even though the motion of interest (a step every half second) is slow. MuJoCo's default timestep is 2 ms (500 Hz). PyBullet's default is 1/240 s.

Asimov's simulation runs physics at 200 Hz. The observation and IO path also runs at 200 Hz, and the policy runs at 50 Hz, producing commanded joint targets from the latest available IO state.

At 200 Hz the physics timestep is 5 ms, and four physics steps pass for every policy decision. That ratio is implied by the rates, not stated as a separate parameter. Chapter 6 explores this multi-rate structure.

Simulation frequency versus real-time execution

Two different clocks are easily confused:

  • Simulation frequency is 1/Δt1/\Delta t: how many steps make up one simulated second. It is a property of the model and determines accuracy and stability. At 200 Hz, one simulated second is always 200 steps, however long they take to compute.
  • Execution speed is how fast those steps are computed relative to the wall clock. It is reported as the real-time factor: simulated seconds per wall-clock second.
Illustrative example

Suppose one step of a legged-robot model takes 25 µs on one CPU core. 200 steps (one simulated second) then take 5 ms of computation, a real-time factor of 200×. Run 4,096 copies in parallel on a GPU and the aggregate is far higher. These numbers are made up for illustration. Real step costs depend on the model, the number of contacts and the hardware.

Training wants the real-time factor as high as possible. The simulation does not "know" how fast it is running, and a 200 Hz model gives identical results at 0.1× or 1000× real time. Some uses need the simulation to run at real time, paced to the wall clock: driving real firmware or a real controller against simulated physics (hardware- or processor-in-the-loop), or a human operating a simulated robot. Then the engine must finish each step faster than Δt\Delta t, and it sleeps for the remainder.

The playback-speed control in the timestep experiment demonstrates this. Changing 0.25× to 4× changes how quickly you see the result, but the trajectories are identical, because the physics only depends on Δt\Delta t. In-browser simulations on this site use exactly this pattern: a fixed physics timestep, an accumulator of wall-clock time, and a display rate that is independent of the physics rate.

Where the data comes from and what format it uses

A physics engine needs two kinds of data: a model that is fixed for a run, and a state that changes every step.

The model describes bodies (mass, centre of mass, inertia tensor), joints (type, axis, limits, damping, friction), actuators (gear ratio, limits, control mode), collision geometry (primitives or meshes, friction coefficients, contact softness) and global options (gravity, timestep, integrator). It is written in a robot description format:

FormatOriginTypical use
URDF (XML)ROSKinematic tree, inertias, meshes. No closed loops. Widely exported from CAD
MJCF (XML)MuJoCoFull MuJoCo model including actuators, contact parameters, tendons and equality constraints
SDF (XML)GazeboWhole worlds: multiple models, lights, sensors, physics settings
USDPixar, adopted by NVIDIA OmniverseScene description used by Isaac Sim, with physics schemas

The numbers in these files come from CAD (masses and inertias computed from geometry and material density), datasheets (motor torque limits, gear ratios), and measurement. System identification fits parameters such as joint friction, armature and actuator delay to data logged on the real robot. Values that cannot be pinned down are often randomised during training, so the policy works across a range of them.

The state is a set of flat numeric arrays, normally 64-bit floats: positions qq (length nqn_q), velocities q˙\dot q (length nvn_v), actuator commands uu, and the simulation time. After each step the engine also exposes derived quantities: body poses, sensor readings, contact lists, and the force terms in the equation of motion. In MuJoCo these live in mjData as qpos, qvel, ctrl, time, contact, qfrc_bias and so on. The model lives in mjModel, compiled once from MJCF or URDF.

  1. CAD + datasheets + measurementsmasses, inertias, limits, friction
  2. Model fileURDF / MJCF / SDF / USD
  3. Compiled modele.g. mjModel: fixed for the run
  4. State arrayse.g. mjData: q, q̇, ctrl, contacts
  5. Observationswhat the policy is allowed to see
Data flow into and out of a physics engine. The model is fixed; the state is overwritten every step.

Code

A minimal integrator in Python

This is a complete, dependency-free simulation of a nonlinear pendulum with semi-implicit Euler. Every robotics engine contains this pattern at its core, in vector form.

pendulum_semi_implicit.py
import math
 
def simulate_pendulum(theta0_deg, length=1.0, g=9.81, dt=0.002, duration=10.0):
    """Integrate theta'' = -(g/L) sin(theta) with semi-implicit Euler."""
    theta = math.radians(theta0_deg)
    omega = 0.0
    t = 0.0
    trajectory = []
    while t < duration:
        alpha = -(g / length) * math.sin(theta)  # dynamics: acceleration from the state
        omega += alpha * dt                      # 1. velocity first
        theta += omega * dt                      # 2. position with the NEW velocity
        t += dt
        trajectory.append((t, theta, omega))
    return trajectory
 
def energy(theta, omega, length=1.0, g=9.81, m=1.0):
    return 0.5 * m * (length * omega) ** 2 + m * g * length * (1 - math.cos(theta))
 
traj = simulate_pendulum(60)
e0 = energy(math.radians(60), 0.0)
t, theta, omega = traj[-1]
print(f"t = {t:.2f} s, theta = {math.degrees(theta):.2f} deg, "
      f"energy drift = {100 * (energy(theta, omega) - e0) / e0:+.3f} %")
python

Swap the two update lines (position first, using the old velocity) and you have explicit Euler. Run it for 100 s and the pendulum gains energy until it swings over the top.

Stepping MuJoCo

The same single-joint arm as the experiment above, in MuJoCo, using the official mujoco Python bindings (pip install mujoco). The model is defined inline in MJCF.

mujoco_arm.py
import mujoco
import numpy as np
 
XML = """
<mujoco model="single_joint_arm">
  <option timestep="0.002" gravity="0 0 -9.81" integrator="Euler"/>
  <worldbody>
    <body name="link" pos="0 0 1">
      <joint name="shoulder" type="hinge" axis="0 1 0" damping="0.05"/>
      <!-- 0.5 m capsule hanging down; its inertia is computed from the shape and mass -->
      <geom type="capsule" fromto="0 0 0 0 0 -0.5" size="0.02" mass="1"/>
    </body>
  </worldbody>
  <actuator>
    <motor name="shoulder_motor" joint="shoulder" gear="1" ctrllimited="true" ctrlrange="-3 3"/>
  </actuator>
</mujoco>
"""
 
model = mujoco.MjModel.from_xml_string(XML)   # compiled, fixed model
data = mujoco.MjData(model)                    # mutable state
 
kp, kd, target = 20.0, 1.0, np.pi / 2          # PD gains and a horizontal target
for step in range(2500):                       # 2500 x 2 ms = 5 s of simulated time
    q, qd = data.qpos[0], data.qvel[0]
    data.ctrl[0] = kp * (target - q) - kd * qd # MuJoCo clips this to ctrlrange
    mujoco.mj_step(model, data)                # kinematics, forces, constraints, integration
    if step % 250 == 0:
        print(f"t={data.time:4.2f} s  q={np.degrees(data.qpos[0]):7.2f} deg  "
              f"bias={data.qfrc_bias[0]:+.3f} N·m  motor={data.qfrc_actuator[0]:+.3f} N·m")
python

mj_step performs the whole pipeline from the previous section. qfrc_bias is the C(q,q˙)C(q,\dot q) term (here, almost entirely gravity), and qfrc_actuator is the motor's contribution to τ\tau. The capsule's inertia differs slightly from an ideal thin rod because of its radius and rounded ends, so the numbers will not match the browser experiment exactly.

For a model with contacts, the contact list is available after each step:

read_contacts.py
force = np.zeros(6)
for i in range(data.ncon):
    c = data.contact[i]
    mujoco.mj_contactForce(model, data, i, force)  # force/torque in the contact frame
    print(f"geoms {c.geom1}-{c.geom2}  dist={c.dist * 1000:+.2f} mm  normal force={force[0]:.1f} N")
python

A negative dist is penetration. With MuJoCo's soft contacts, a small negative value under load is normal and expected.

Physics engines and simulation platforms

"Simulator" is used loosely for two different things. A physics engine is the library that implements step. A simulation platform wraps one or more engines with everything else a robotics project needs: model loading, sensor simulation, rendering, a GUI, middleware such as ROS, and tools for running experiments. Mixing the two levels up leads to comparisons like "Gazebo vs MuJoCo" that compare a platform with an engine.

NameWhat it isPhysicsNotes
MuJoCoPhysics engineIts own: generalised coordinates, soft convex contact optimisationCreated by Emo Todorov (Todorov, Erez and Tassa, IROS 2012). Acquired by DeepMind in 2021 and open-sourced under Apache 2.0 in 2022. Python bindings, MJCF models. MJX is a JAX reimplementation for GPU/TPU batch simulation. Widely used for locomotion and RL research
Bullet / PyBulletPhysics engine / its Python bindingsBullet: maximal-coordinate rigid bodies plus a Featherstone multibody solverBullet is by Erwin Coumans. PyBullet is the Python module, convenient for quick experiments and URDF loading. Default timestep 1/240 s
ODE, DART, SimbodyPhysics enginesODE: maximal coordinates. DART: generalised coordinates (Featherstone-style)Best known in robotics as engines that Gazebo can use
PhysXPhysics engine (NVIDIA)Rigid bodies, articulations (reduced coordinates), GPU accelerationAlso used in game engines. The physics inside Isaac Sim
GazeboSimulation platformPluggable enginesGazebo Classic offered ODE (default), Bullet, Simbody and DART. The current Gazebo (formerly Ignition) loads engines as plugins through its gz-physics layer, with DART as the default at the time of writing. Strong ROS integration, SDF worlds, sensor plugins
Isaac SimSimulation platform (NVIDIA, built on Omniverse)PhysXUSD scenes, photorealistic rendering, GPU-parallel simulation. Isaac Lab builds RL training workflows on top of it

Engines differ in exactly the places this chapter has discussed: coordinates (reduced or maximal), contact model (soft or hard, how friction is approximated), default integrator and timestep, and solver. The same robot model can therefore behave differently in two engines. Comparative studies (for example Erez, Tassa and Todorov, 2015) found that no engine wins on every task. Details change between versions, so check the current documentation of whichever tool you use. Treat the table above as orientation, not specification.

Asimov's simulation is built on MuJoCo. During processor-in-the-loop validation, a MuJoCo bridge reads the simulated IMU's angular velocity and linear acceleration and sends them to the firmware over UDP.

A practical robotics example: one foot touching the ground

Follow one 5 ms physics step of a walking biped at the moment its swing foot lands.

  1. State. The foot is moving down at 0.3 m/s and forward at 0.1 m/s. Joint angles and velocities for both legs and the floating-base pose are in qq and q˙\dot q.
  2. Collision detection. The capsule at the heel now overlaps the floor plane by a fraction of a millimetre. The narrow phase reports two contact points along the capsule's line, with the floor normal pointing up.
  3. Smooth forces. Gravity, Coriolis terms and the motor torques from the low-level PD loops (which track the policy's latest joint targets, saturated at the motor limits) are added up.
  4. Contact solve. The solver finds normal and friction forces at the new contacts, and at the stance foot's existing contacts, such that the heel stops sinking, the friction force stays inside the friction cone, and both feet together carry the robot's weight. If the required friction would leave the cone, the solution includes slip.
  5. Integrate. Accelerations update velocities, velocities update positions, and time advances by 5 ms. The heel's downward velocity is now close to zero, and the impact has propagated up the leg as a change in every joint's velocity.

Four such steps later the policy, running at 50 Hz, reads a new observation (joint angles, joint velocities, IMU-like signals) and outputs new joint targets. The contact forces it never sees directly shaped every one of those values. That is why contact modelling choices (Chapter 6) and what the policy is allowed to observe (Chapter 8) are so tightly linked.

How this connects to the rest of the site

  • Chapter 1 placed the physics engine in the perception–action loop as the environment block.
  • Chapter 3 opens up one engine, MuJoCo: mjModel, mjData, and what happens inside mj_step().
  • Chapter 4 covers how simulated sensors are computed from the engine's state, and why the real ones are noisier and later.
  • Chapter 6 applies all of this to a real humanoid model: capsule feet, passive toes, actuator models and multi-rate timing.
  • Chapter 7 onwards treats the engine as the environment an RL agent learns from. Every reward is computed from engine state.

Limitations and common misconceptions

“A physics engine simulates reality.”

It simulates a model: rigid bodies, idealised joints, a chosen contact law, approximate friction, at a finite timestep. Every one of those is a simplification. A good engine is one whose simplifications do not matter for your task.

“Smaller timesteps are always better.”

Smaller steps improve accuracy and stability, but cost proportionally more computation, and for RL that means fewer samples per hour. Once the error from integration is well below the error from the model itself (unknown friction, mass errors), shrinking the step further gains nothing. The usual approach is to choose the largest step that is stable and accurate for the stiffest element in the model.

“Static friction is a constant force μs·N.”

μs·N is the maximum static friction. Below that, friction equals whatever is needed to prevent sliding, which may be zero. The friction experiment shows friction tracking the applied force exactly until breakaway.

“Penetration means the simulation is broken.”

Many engines, MuJoCo included, deliberately allow small, controlled penetration because perfectly rigid contact is numerically difficult. What matters is that the penetration is small, consistent and bounded. A visibly sinking robot means the contact is too soft. Exploding contacts mean it is too stiff for the timestep.

“If the energy is conserved, the simulation is correct.”

Semi-implicit Euler keeps energy bounded even at timesteps where its trajectory is clearly wrong. Conservation is a useful sanity check, not a proof of accuracy.

Things physics engines usually do not model well

Deformable bodies (soft feet, cables, compliant grippers), gear backlash, motor thermal limits, impacts with very short durations, and friction that depends on velocity or history. Where these matter, they are added as extra models (actuator networks, compliance, randomisation) or accepted as part of the sim-to-real gap.

Key takeaways

Key takeaways

  • A physics engine implements one function: next state = step(state, controls, Δt). Rendering is separate and optional.
  • Newton's second law, in matrix form M(q)q¨+C(q,q˙)=τ+J⊤fM(q)\ddot q + C(q,\dot q) = \tau + J^\top f, is what the engine solves every step. The unknown contact forces ff are the hard part.
  • Each step runs kinematics and collision detection, adds up smooth forces, solves for constraint and contact forces, then integrates.
  • Inertia depends on mass distribution; torque needed against gravity grows with sin⁡θ\sin\theta and link length; real motors saturate.
  • Static friction adapts up to μs·N, then drops to μk·N once sliding. Robots slip when the foot force leaves the friction cone.
  • Contact can be soft (penalty, small penetration, needs small timesteps) or hard (impulses, constraint solvers). MuJoCo uses soft constraints solved as a convex optimisation.
  • The integrator and timestep change the answer. Explicit Euler invents energy, semi-implicit Euler keeps it bounded, RK4 is accurate but costlier, and every method fails when ωΔt\omega\Delta t is too large.
  • Simulation frequency (1/Δt) sets accuracy. Real-time factor sets how fast results arrive. They are independent.
  • MuJoCo, Bullet, ODE, DART and PhysX are engines. Gazebo and Isaac Sim are platforms built on top of engines.

References and further reading

  • E. Todorov, T. Erez and Y. Tassa, "MuJoCo: A physics engine for model-based control," IEEE/RSJ IROS, 2012.
  • MuJoCo documentation, mujoco.readthedocs.io, especially the Overview, Computation and Python chapters.
  • R. Featherstone, Rigid Body Dynamics Algorithms (Springer, 2008). The standard reference for RNEA, ABA and generalised-coordinate dynamics.
  • K. M. Lynch and F. C. Park, Modern Robotics: Mechanics, Planning, and Control (Cambridge University Press, 2017). Free preprint and videos.
  • T. Erez, Y. Tassa and E. Todorov, "Simulation tools for model-based robotics: Comparison of Bullet, Havok, MuJoCo, ODE and PhysX," IEEE ICRA, 2015.
  • D. E. Stewart and J. C. Trinkle, "An implicit time-stepping scheme for rigid body dynamics with inelastic collisions and Coulomb friction," International Journal for Numerical Methods in Engineering, 1996.
  • E. Hairer, C. Lubich and G. Wanner, Geometric Numerical Integration, 2nd ed. (Springer, 2006), on symplectic integrators and long-time energy behaviour.
  • A. Witkin and D. Baraff, Physically Based Modeling, SIGGRAPH course notes. A readable introduction to rigid bodies, constraints and collision.
  • E. Coumans and Y. Bai, PyBullet and the PyBullet Quickstart Guide.
  • Gazebo documentation, including the gz-physics engine plugins.
  • NVIDIA, Isaac Sim documentation, and the PhysX SDK documentation.
  • Menlo, Understanding Your Simulation Environment, for how these ideas are applied to Asimov.