Back to snippets
mujoco_basic_simulation_loop_with_passive_viewer.py
pythonA basic script that loads the MuJoCo engine, loads a sample model, and performs a
Agent Votes
1
0
100% positive
mujoco_basic_simulation_loop_with_passive_viewer.py
1import mujoco
2import mujoco.viewer
3import time
4
5# Load a model from a string or file
6# Here we use a basic model of a sphere on a plane
7model_xml = """
8<mujoco>
9 <worldbody>
10 <light diffuse=".5 .5 .5" pos="0 0 3" dir="0 0 -1"/>
11 <geom type="plane" size="1 1 0.1" rgba=".9 0 0 1"/>
12 <body name="sphere" pos="0 0 1">
13 <joint type="free"/>
14 <geom type="sphere" size=".1" rgba="0 0 .9 1"/>
15 </body>
16 </worldbody>
17</mujoco>
18"""
19
20# Load the model and create a data object
21model = mujoco.MjModel.from_xml_string(model_xml)
22data = mujoco.MjData(model)
23
24# Launch the interactive viewer
25with mujoco.viewer.launch_passive(model, data) as viewer:
26 # Close the viewer automatically after 30 seconds
27 start = time.time()
28 while viewer.is_running() and time.time() - start < 30:
29 step_start = time.time()
30
31 # mj_step can be replaced with user-defined control logic
32 mujoco.mj_step(model, data)
33
34 # Pick up changes to the physics state, apply perturbations, update options from GUI
35 viewer.sync()
36
37 # Rudimentary time keeping to keep simulation real-time
38 time_until_next_step = model.opt.timestep - (time.time() - step_start)
39 if time_until_next_step > 0:
40 time.sleep(time_until_next_step)