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:
- is the state at step : every joint angle and velocity, plus the position, orientation and velocity of any free-floating body such as a robot's pelvis.
- is the control input: motor torques, or targets that a simulated motor controller turns into torques.
- 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 engine | Physics engine | |
|---|---|---|
| Question it answers | What does the scene look like from this camera? | Where will everything be after ? |
| Main inputs | Meshes, materials, lights, camera pose | Masses, inertias, joints, forces, contact geometry |
| Output | Pixels | New positions, velocities, contact forces |
| Typical rate | 30–120 frames per second, tied to the display | 200–1000+ steps per second, tied to accuracy and stability |
| What an error looks like | A wrong colour or shadow | A 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 cameras | Always |
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:
- Design checks. Before building a leg you want to know whether a motor can lift it. That needs dynamics, not drawings.
- Safety and cost. A policy that falls 10,000 times while learning would destroy real hardware. In simulation a fall costs a reset.
- 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:
- First law (inertia). A body keeps its velocity, which may be zero, unless a net force acts on it.
- Second law. The net force equals mass times acceleration: . Force and acceleration are vectors and point the same way.
- Third law. When body A pushes on body B with force , B pushes on A with . 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 , 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 , where . Because the force is proportional to mass, the acceleration 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
A ball dropped from 5 m on Earth lands after s at 9.90 m/s. On the Moon () it takes 2.48 s and lands at 4.02 m/s.
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 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 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:
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 .
Inertia
Inertia is resistance to changes in motion. For straight-line motion it is just mass. For rotation it is the moment of inertia (kg·m²), which depends on how the mass is distributed about the rotation axis:
Mass far from the axis counts much more than mass close to it, because of the . A uniform rod of mass and length has about its centre but 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
measured in newton-metres (N·m). The rotational form of Newton's second law is
where is angular acceleration (rad/s²). Angular velocity (rad/s) and angle (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 with its centre of mass at distance from the joint, at angle from hanging straight down:
At (horizontal) the torque is largest. A 1 kg, 0.5 m uniform link ( m) needs 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: for the centre of mass and for rotation. The extra term 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 : the free-floating base pose plus one coordinate per joint degree of freedom. In these coordinates the whole robot obeys one matrix equation:
| Symbol | Meaning | Size for a robot with velocity DoF |
|---|---|---|
| positions, velocities, accelerations in generalised coordinates | (positions can be longer, see below) | |
| mass matrix: the inertia "felt" by each coordinate, including coupling between joints | , symmetric, positive definite | |
| bias forces: gravity, Coriolis and centrifugal effects | ||
| actuator torques and other applied generalised forces (springs, joint damping) | ||
| contact Jacobian: maps to the velocity of each contact point | for point contacts | |
| contact and constraint forces (normal force and friction at each contact) |
converts forces at the feet into their effect on every joint. If the contact forces were known, forward dynamics would just be . The hard part is that is not known in advance. It depends on the motion, and the motion depends on it. Finding is the job of the contact solver, discussed below.
Computing , 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.
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 velocity DoF and 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:
| Joint | Free motion | DoF | Robot example |
|---|---|---|---|
| Hinge (revolute) | rotation about one axis | 1 | knee, hip pitch |
| Slide (prismatic) | translation along one axis | 1 | linear actuator, gantry |
| Ball (spherical) | any rotation | 3 | shoulder approximated as one joint |
| Free | any translation and rotation | 6 | floating base of a legged robot |
| Fixed (weld) | none | 0 | rigidly 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:
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.
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 rad to generate the 2.45 N·m that gravity demands. Raise 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 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 () 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 and unknowns to 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: .
- Kinetic (sliding). Once sliding, friction has magnitude and opposes the sliding velocity. Usually .
Here is the normal force pressing the surfaces together, and the coefficients 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 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.
With the defaults (2 kg on flat ground, , ), 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 N, at about 5.9 s. The block then breaks loose and friction drops to 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 , at . 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:
- 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.
- 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 at each one. Physically, rigid contact satisfies three conditions:
- The bodies do not interpenetrate (gap ).
- The normal force only pushes, never pulls ().
- Force acts only when touching: . 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:
| Approach | Idea | Strengths | Weaknesses |
|---|---|---|---|
| Penalty (soft) contact | Allow a small overlap and push back with a spring–damper | Simple, smooth, easy to differentiate | Stiff springs need tiny timesteps. Soft springs let objects sink and bounce |
| Impulse / velocity-level (hard) contact | Change velocities instantaneously so contacts stop approaching, then correct any overlap | Stable with larger timesteps, no visible sinking | Collisions 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 problem | Handles many coupled contacts with friction | Expensive, 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.
Things to try:
- In penalty mode, drag the stiffness down to N/m. The discs sink visibly into the floor. A resting disc settles at , which is 31 mm for the 1 kg disc. At the default N/m it is 0.31 mm.
- Set . The contact becomes a perfect spring and the discs keep bouncing. Raise towards 1 and impacts are absorbed.
- Push stiffness to 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:
- 1Current stateq, q̇, time t
- 2Kinematics + collision detectionbody poses, contact points, normals, depths
- 3Smooth forcesgravity, Coriolis C(q,q̇), actuator τ, springs, damping
- 4Constraint & contact solvefind f: no penetration, friction cone, joint limits
- 5Integrateq̈ → q̇ → q, advance t by Δt
Loops back: Integrate → Current state
In equations, for one step of length :
The 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: kg, m, so kg·m². The arm is horizontal (), momentarily still (), and the motor applies N·m. The timestep is 2 ms. There are no contacts.
- State: rad, .
- Kinematics: the centre of mass is 0.25 m out, horizontally.
- Forces: gravity torque N·m. Damping . Net torque N·m.
- Dynamics: rad/s².
- Integrate (semi-implicit Euler): rad/s, then 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 , :
- Explicit (forward) Euler uses the values at the start of the step for both updates: , . 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: , . 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 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
implicitandimplicitfastintegrators treat velocity-dependent forces this way.
"First-order" and "fourth-order" describe how the error per unit time shrinks with the timestep: proportionally to for Euler, to for RK4.
Before comparing integrators, here is a system where we know the right answer. A pendulum's small-angle period is , which is 2.006 s for m. That formula assumes . The experiment integrates the full nonlinear equation with RK4 and shows the small-angle solution as a ghost.
Released at 10°, the two pendulums stay together for many swings. Released at 90°, the true period is 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.
With the spring–mass defaults ( N/m, kg, so rad/s, and ms, so ):
- Explicit Euler spirals outward in the phase portrait. For this system its energy grows by exactly 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 . Try N/m and s.
- RK4 is almost indistinguishable from the exact solution. Its position error after 10 s is about m at this step size, and halving cuts it roughly sixteenfold.
Two rules follow, and both apply directly to robot simulation:
- The timestep must be small compared with the fastest motion in the system. The relevant quantity is , where 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 N/m on 1 kg has rad/s. Semi-implicit Euler is stable only if ms, and it is accurate only well below that.
- Stable is not the same as accurate. Semi-implicit Euler at 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 : 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.
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 , 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 . 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:
| Format | Origin | Typical use |
|---|---|---|
| URDF (XML) | ROS | Kinematic tree, inertias, meshes. No closed loops. Widely exported from CAD |
| MJCF (XML) | MuJoCo | Full MuJoCo model including actuators, contact parameters, tendons and equality constraints |
| SDF (XML) | Gazebo | Whole worlds: multiple models, lights, sensors, physics settings |
| USD | Pixar, adopted by NVIDIA Omniverse | Scene 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 (length ), velocities (length ), actuator commands , 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.
- CAD + datasheets + measurementsmasses, inertias, limits, friction
- Model fileURDF / MJCF / SDF / USD
- Compiled modele.g. mjModel: fixed for the run
- State arrayse.g. mjData: q, q̇, ctrl, contacts
- Observationswhat the policy is allowed to see
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.
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} %")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.
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")mj_step performs the whole pipeline from the previous section. qfrc_bias is the term (here, almost entirely gravity), and qfrc_actuator is the motor's contribution to . 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:
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")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.
| Name | What it is | Physics | Notes |
|---|---|---|---|
| MuJoCo | Physics engine | Its own: generalised coordinates, soft convex contact optimisation | Created 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 / PyBullet | Physics engine / its Python bindings | Bullet: maximal-coordinate rigid bodies plus a Featherstone multibody solver | Bullet is by Erwin Coumans. PyBullet is the Python module, convenient for quick experiments and URDF loading. Default timestep 1/240 s |
| ODE, DART, Simbody | Physics engines | ODE: maximal coordinates. DART: generalised coordinates (Featherstone-style) | Best known in robotics as engines that Gazebo can use |
| PhysX | Physics engine (NVIDIA) | Rigid bodies, articulations (reduced coordinates), GPU acceleration | Also used in game engines. The physics inside Isaac Sim |
| Gazebo | Simulation platform | Pluggable engines | Gazebo 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 Sim | Simulation platform (NVIDIA, built on Omniverse) | PhysX | USD 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.
- 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 and .
- 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.
- 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.
- 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.
- 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 insidemj_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 , is what the engine solves every step. The unknown contact forces 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 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 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.