Simulation9 min read

Install MuJoCo and simulate a falling sphere in Python

Set up Google DeepMind's official MuJoCo 4 Python bindings in an isolated virtual environment, understand MjModel vs. MjData, and run a deterministic headless physics simulation.

Ramon GoveiaEditor, PolarisonPublished Checked against official sources

Key takeaways

  1. 01MuJoCo (Multi-Joint dynamics with Contact) is Google DeepMind's open-source physics engine and the de facto backbone for robotics research, reinforcement learning (Gymnasium, dm_control), and biomechanics. Historically, getting MuJoCo running on Windows meant wrestling with commercial license keys, C compilers, and the now-deprecated mujoco-py wrapper.
  2. 02MuJoCo's MjModel/MjData split gives you deterministic, C-speed physics from a 20-line Python script. Keep your baseline headless and reproducible, then vary one physical parameter at a time.

Why this tool matters

The official mujoco Python package eliminates all of that friction: precompiled wheels ship with the C physics engine bundled inside, install in seconds inside a standard venv, and run headlessly without needing OpenGL or a desktop window. That makes it ideal for automated CI physics tests, parameter sweeps, and high-throughput reinforcement learning loops.

In this walkthrough, we explain MuJoCo's data-oriented memory architecture (MjModel vs. MjData), compare it with PyBullet and NVIDIA Isaac Lab, install pinned version 4.0.1 on Windows, and build a minimal MJCF falling-sphere experiment that verifies contact settling mathematically.

Watch the walkthrough

Under the hood: why MuJoCo separates MjModel and MjData

Developers arriving from game engines often expect an object-oriented tree such as sphere.position.z. MuJoCo deliberately avoids object hierarchies in favor of two flat, cache-friendly C structs exposed directly to Python as NumPy arrays: MjModel and MjData.

This split is what lets MuJoCo step complex articulated robots thousands of times per second on a single CPU core and lets you run multiple parallel rollouts sharing the exact same compiled physics blueprint.

  • MjModel (immutable blueprint): compiled once from MJCF XML. Holds static geometry, masses, joint limits, gravity, timestep (opt.timestep, default 0.002s), and name-to-ID lookup tables.
  • MjData (mutable simulation state): holds every time-varying array — generalized positions (qpos), velocities (qvel), actuator controls (ctrl), world-frame body positions (xpos), and contact forces.
  • Why a free joint has 7 qpos values and 6 qvel values: an unconstrained 3D body needs 3 Cartesian coordinates (x, y, z) plus a 4-element unit quaternion (w, x, y, z) for singularity-free orientation, while its velocity uses 3 linear and 3 angular components.
  • Headless execution: calling mj_forward and mj_step computes pure C dynamics with zero graphics overhead. You only import mujoco.viewer when you explicitly want an interactive 3D window.

How it compares to alternatives

ToolBest forMain tradeoff
MuJoCo (official Python bindings)Fast, accurate contact-rich robotics, RL benchmarks, and headless Python automation on CPU or MJX (JAX).Minimal built-in photorealistic rendering compared to full game-engine simulators.
NVIDIA Isaac Lab / Isaac SimMassively parallel GPU simulation (thousands of environments) with photorealistic camera sensors.Requires high-end NVIDIA RTX GPU, heavy multi-gigabyte install, and steeper setup on Windows.
PyBulletQuick educational prototypes and legacy URDF demos.Older contact solver, slower maintenance cadence, and less accurate joint dynamics than MuJoCo.
Genesis / BraxDifferentiable physics and pure JAX/PyTorch end-to-end GPU training pipelines.Smaller ecosystem of pre-built robot models compared to MuJoCo Menagerie.

Step-by-step walkthrough

  1. Create an isolated virtual environment and pin MuJoCo 4.0.1

    Create a clean .venv inside an empty working folder and invoke its Python executable directly. Calling .venv\Scripts\python.exe avoids PowerShell execution-policy prompts and keeps your global Python installation untouched. Pinning mujoco==4.0.1 guarantees your contact solver behavior and XML schema stay reproducible across machines.

    • Never install the deprecated mujoco-py package — it is unmaintained and incompatible with modern MuJoCo releases.
    • The official wheel bundles the native C library, so no Visual Studio C++ Build Tools are required on Windows.
    python -m venv .venv
    .venv\Scripts\python.exe -m pip install mujoco==4.0.1
  2. Define the MJCF scene and step the simulation in Python

    Save the script below as fall.py. Inside the <worldbody>, the static plane acts as an infinite floor at z = 0, while the named ball body starts at z = 1.0 metres with a <freejoint/> giving it 6 degrees of freedom. Calling mj_forward(model, data) computes derived kinematics (xpos) at t = 0 before any time passes, and the loop advances 500 steps (1.0 second at the default 2 ms timestep).

    • model.body('ball').id resolves the named body to its integer index in data.xpos, avoiding hardcoded magic indices.
    • data.xpos[ball, 2] reads the world-frame vertical (z) coordinate of the sphere's centre of mass.
    import mujoco
    
    xml = '''<mujoco>
      <worldbody>
        <geom type="plane" size="2 2 0.1"/>
        <body name="ball" pos="0 0 1">
          <freejoint/>
          <geom type="sphere" size="0.1"/>
        </body>
      </worldbody>
    </mujoco>'''
    
    model = mujoco.MjModel.from_xml_string(xml)
    data = mujoco.MjData(model)
    mujoco.mj_forward(model, data)
    
    ball = model.body('ball').id
    print(f'Start z: {data.xpos[ball, 2]:.3f} m')
    for _ in range(500):
        mujoco.mj_step(model, data)
    print(f'Final z: {data.xpos[ball, 2]:.3f} m')
  3. Run headlessly and interpret the physical result

    Execute the script from PowerShell. Under standard Earth gravity (-9.81 m/s²), a sphere dropped from 1.000 m reaches the plane in roughly 0.43 seconds and settles with its centre at 0.100 m — equal to its radius (size="0.1"). Notice that the entire 500-step simulation completes in milliseconds without opening any GUI window.

    • A tiny discrepancy (e.g., 0.099 m vs 0.100 m) is normal: MuJoCo uses soft constraint-based contacts (solref / solimp) for numerical stability.
    • To inspect the full trajectory, print (data.time, data.xpos[ball, 2]) every 25 steps or log data.qpos into a CSV.
    .venv\Scripts\python.exe fall.py
  4. Extend the experiment: vary one parameter at a time

    Now that you have a deterministic baseline, test how MuJoCo responds to physical changes: adjust <option timestep="0.001" gravity="0 0 -1.62"/> to simulate lunar gravity, or add elasticity with solref="-1000 -10" on the sphere geom to observe repeated bounces before settling.

    • When you are ready to visualize complex articulated robots, launch the built-in viewer with mujoco.viewer.launch_passive(model, data) and pull ready-made models from Google DeepMind's MuJoCo Menagerie.

MuJoCo's MjModel/MjData split gives you deterministic, C-speed physics from a 20-line Python script. Keep your baseline headless and reproducible, then vary one physical parameter at a time.

Common pitfalls

Forgetting mj_forward() before reading xpos at t = 0

Right after constructing MjData(model), derived world positions (xpos) are all zeros until you call mj_forward(model, data) or take a step.

Omitting <freejoint/> on a dynamic body

Without a joint element, a <body> is welded rigidly to the world frame and will hover at z = 1.0 forever despite gravity.

Using too large a timestep for stiff contacts

Increasing timestep above 0.01s can cause interpenetration or energy blow-up on small, lightweight objects. Keep the default 0.002s unless you benchmark stability.

Frequently asked questions

Do I need a GPU to run MuJoCo in Python?
No. Standard MuJoCo runs natively on CPU and is extremely fast for single or dozens of environments. You only need a GPU if you use MJX (JAX-accelerated MuJoCo) for thousands of parallel RL environments.
Can MuJoCo load URDF robot files instead of MJCF?
Yes. `MjModel.from_xml_path('robot.urdf')` compiles standard ROS URDF files directly, though MJCF offers finer control over actuators, tendons, and contact parameters.
How do I run MuJoCo in CI/CD pipelines without a display?
Pure physics stepping (`mj_step`) never touches OpenGL and runs on headless Linux or Windows runners out of the box. For offscreen camera images, configure `MUJOCO_GL=egl` or `osmesa` on Linux.

Sources and methodology

Every command in this guide was run on a clean Windows machine before publishing, and the video shows that run. Versions are pinned where the project publishes them, so the output you see should match ours.

Keep reading