Interacting with a rigid object#
This is the first runtime example in Assets: spawn a rigid body, reset its state, step the simulation, and read the updated state. Use the authoring guides for configuration details and Interacting with an articulation for bodies connected by joints.
Use assets.RigidObject to read and write the spawned object’s state.
Explore rigid-body contacts by toppling a compact domino scene. Change friction and reset to replay the cascade, then follow the tutorial below to spawn and control your own rigid objects.
Interactive demos load when this section is visible.
The Code#
The tutorial corresponds to the run_rigid_object.py script in the scripts/tutorials/01_assets directory.
Code for run_rigid_object.py
1# Copyright (c) 2022-2026, The Isaac Lab Project Developers (https://github.com/isaac-sim/IsaacLab/blob/main/CONTRIBUTORS.md).
2# All rights reserved.
3#
4# SPDX-License-Identifier: BSD-3-Clause
5
6"""
7This script demonstrates how to create a rigid object and interact with it.
8
9.. code-block:: bash
10
11 # Usage
12 uv run --extra ov python scripts/tutorials/01_assets/run_rigid_object.py
13
14"""
15
16"""Parse the command-line arguments first."""
17
18
19import argparse
20from types import SimpleNamespace
21
22from isaaclab_ov.physics import OvPhysxCfg
23
24from isaaclab.app import add_launcher_args, launch_simulation
25from isaaclab.scene import InteractiveSceneCfg
26from isaaclab.utils import instantiate
27
28# add argparse arguments
29parser = argparse.ArgumentParser(description="Tutorial on spawning and interacting with a rigid object.")
30# append simulation launcher cli args
31add_launcher_args(parser)
32parser.set_defaults(visualizer=["newton_rtx"])
33# parse the arguments
34args_cli = parser.parse_args()
35
36"""Rest everything follows."""
37
38import torch
39
40import isaaclab.sim as sim_utils
41import isaaclab.utils.math as math_utils
42from isaaclab.assets import AssetBaseCfg, RigidObject, RigidObjectCfg
43from isaaclab.sim import SimulationContext
44
45
46def design_scene():
47 """Designs the scene."""
48 # Ground-plane
49 cfg = sim_utils.GroundPlaneCfg()
50 cfg.func("/World/defaultGroundPlane", cfg)
51 # Lights
52 cfg = sim_utils.DomeLightCfg(intensity=2000.0, color=(0.8, 0.8, 0.8))
53 cfg.func("/World/Light", cfg)
54
55 # Create separate groups called "Origin1", "Origin2", "Origin3"
56 # Each group will have a robot in it
57 origins = [[0.25, 0.25, 0.0], [-0.25, 0.25, 0.0], [0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]]
58 for i, origin in enumerate(origins):
59 sim_utils.create_prim(f"/World/Origin{i}", "Xform", translation=origin)
60
61 # Rigid Object
62 cone_cfg = RigidObjectCfg(
63 prim_path="/World/Origin.*/Cone",
64 spawn=sim_utils.ConeCfg(
65 radius=0.1,
66 height=0.2,
67 rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(),
68 mass_props=sim_utils.MassCfg(mass=1.0),
69 collision_props=sim_utils.UsdPhysicsCollisionCfg(),
70 visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0), metallic=0.2),
71 ),
72 init_state=RigidObjectCfg.InitialStateCfg(),
73 )
74 cone_object = RigidObject(cfg=cone_cfg)
75
76 # return the scene information
77 scene_entities = {"cone": cone_object}
78 return scene_entities, origins
79
80
81def run_simulator(sim: sim_utils.SimulationContext, entities: dict[str, RigidObject], origins: torch.Tensor):
82 """Runs the simulation loop."""
83 # Extract scene entities
84 # note: we only do this here for readability. In general, it is better to access the entities directly from
85 # the dictionary. This dictionary is replaced by the InteractiveScene class in the next tutorial.
86 cone_object = entities["cone"]
87 # Define simulation stepping
88 sim_dt = sim.get_physics_dt()
89 sim_time = 0.0
90 count = 0
91 # Simulate physics
92 while sim.is_running():
93 # reset
94 if count % 250 == 0:
95 # reset counters
96 sim_time = 0.0
97 count = 0
98 # reset root state
99 root_pose = cone_object.data.default_root_pose.torch.clone()
100 # sample a random position on a cylinder around the origins
101 root_pose[:, :3] += origins
102 root_pose[:, :3] += math_utils.sample_cylinder(
103 radius=0.1, h_range=(0.25, 0.5), size=cone_object.num_instances, device=cone_object.device
104 )
105 # write root state to simulation
106 cone_object.write_root_pose_to_sim_index(root_pose=root_pose)
107 root_vel = cone_object.data.default_root_vel.torch.clone()
108 cone_object.write_root_velocity_to_sim_index(root_velocity=root_vel)
109 # reset buffers
110 cone_object.reset()
111 print("----------------------------------------")
112 print("[INFO]: Resetting object state...")
113 # apply sim data
114 cone_object.write_data_to_sim()
115 # perform step
116 sim.step()
117 # update sim-time
118 sim_time += sim_dt
119 count += 1
120 # update buffers
121 cone_object.update(sim_dt)
122 # print the root position
123 if count % 50 == 0:
124 print(f"Root position (in world): {cone_object.data.root_pos_w.torch}")
125
126
127def main():
128 """Main function."""
129 # Configure the simulation
130 sim_cfg = sim_utils.SimulationCfg(
131 physics=OvPhysxCfg(),
132 device=args_cli.device,
133 )
134 # Launch the simulator runtime that the configuration needs
135 scene_cfg = InteractiveSceneCfg(num_envs=1, env_spacing=0.0)
136 scene_cfg.world = AssetBaseCfg(prim_path="/World")
137 with launch_simulation(SimpleNamespace(sim=sim_cfg, scene=scene_cfg), args_cli):
138 # Initialize the simulation context
139 sim = SimulationContext(sim_cfg)
140 # Set main camera
141 sim.set_camera_view(eye=[1.5, 0.0, 1.0], target=[0.0, 0.0, 0.0])
142 # Design scene
143 scene_entities, scene_origins = design_scene()
144 scene_origins = torch.tensor(scene_origins, device=sim.device)
145 _scene = instantiate(scene_cfg)
146 # Play the simulator
147 sim.reset()
148 # Now we are ready!
149 print("[INFO]: Setup complete...")
150 # Run the simulator
151 run_simulator(sim, scene_entities, scene_origins)
152
153
154if __name__ == "__main__":
155 # run the main function
156 main()
The Code Explained#
In this script, we split the main function into two separate functions, which highlight the two main
steps of setting up any simulation in the simulator:
Design scene: As the name suggests, this part is responsible for adding all the prims to the scene.
Run simulation: This part is responsible for stepping the simulator, interacting with the prims in the scene, e.g., changing their poses, and applying any commands to them.
A distinction between these two steps is necessary because the second step only happens after the first step is complete and the simulator is reset. Once the simulator is reset (which automatically plays the simulation), no new (physics-enabled) prims should be added to the scene as it may lead to unexpected behaviors. However, the prims can be interacted with through their respective handles.
Designing the scene#
Similar to the previous tutorial, we populate the scene with a ground plane and a light source. In addition,
we add a rigid object to the scene using the assets.RigidObject class. This class is responsible for
spawning the prims at the input path and initializes their corresponding rigid body physics handles.
In this tutorial, we create a conical rigid object using the spawn configuration similar to the rigid cone
in the Spawn Objects tutorial. The only difference is that now we wrap
the spawning configuration into the assets.RigidObjectCfg class. This class contains information about
the asset’s spawning strategy, default initial state, and other meta-information. When this class is passed to
the assets.RigidObject class, it spawns the object and initializes the corresponding physics handles
when the simulation is played.
As an example on spawning the rigid object prim multiple times, we create its parent Xform prims,
/World/Origin{i}, that correspond to different spawn locations. When the regex expression
/World/Origin.*/Cone is passed to the assets.RigidObject class, it spawns the rigid object prim at
each of the /World/Origin{i} locations. For instance, if /World/Origin1 and /World/Origin2 are
present in the scene, the rigid object prims are spawned at the locations /World/Origin1/Cone and
/World/Origin2/Cone respectively.
# Create separate groups called "Origin1", "Origin2", "Origin3"
# Each group will have a robot in it
origins = [[0.25, 0.25, 0.0], [-0.25, 0.25, 0.0], [0.25, -0.25, 0.0], [-0.25, -0.25, 0.0]]
for i, origin in enumerate(origins):
sim_utils.create_prim(f"/World/Origin{i}", "Xform", translation=origin)
# Rigid Object
cone_cfg = RigidObjectCfg(
prim_path="/World/Origin.*/Cone",
spawn=sim_utils.ConeCfg(
radius=0.1,
height=0.2,
rigid_props=sim_utils.UsdPhysicsRigidBodyCfg(),
mass_props=sim_utils.MassCfg(mass=1.0),
collision_props=sim_utils.UsdPhysicsCollisionCfg(),
visual_material=sim_utils.PreviewSurfaceCfg(diffuse_color=(0.0, 1.0, 0.0), metallic=0.2),
),
init_state=RigidObjectCfg.InitialStateCfg(),
)
cone_object = RigidObject(cfg=cone_cfg)
Since we want to interact with the rigid object, we pass this entity back to the main function. This entity
is then used to interact with the rigid object in the simulation loop. In later tutorials, we will see a more
convenient way to handle multiple scene entities using the scene.InteractiveScene class.
# return the scene information
scene_entities = {"cone": cone_object}
return scene_entities, origins
Running the simulation loop#
We modify the simulation loop to interact with the rigid object to include three steps – resetting the simulation state at fixed intervals, stepping the simulation, and updating the internal buffers of the rigid object. For the convenience of this tutorial, we extract the rigid object’s entity from the scene dictionary and store it in a variable.
Resetting the simulation state#
To reset the simulation state of the spawned rigid object prims, we need to set their pose and velocity. Together they define the root state of the spawned rigid objects. It is important to note that this state is defined in the simulation world frame, and not of their parent Xform prim. This is because the physics engine only understands the world frame and not the parent Xform prim’s frame. Thus, we need to transform desired state of the rigid object prim into the world frame before setting it.
We use the default_root_pose and
default_root_vel attributes of the rigid object’s data
(RigidObject.data) to get the default root state of the spawned rigid object prims. This default state
can be configured from the assets.RigidObjectCfg.init_state attribute, which we left as identity in this
tutorial. We then randomize the translation of the root state and
set the desired state of the rigid object prim using the assets.RigidObject.write_root_pose_to_sim_index() and assets.RigidObject.write_root_velocity_to_sim_index() methods.
As the name suggests, this method writes the root state of the rigid object prim into the simulation buffer.
# reset root state
root_pose = cone_object.data.default_root_pose.torch.clone()
# sample a random position on a cylinder around the origins
root_pose[:, :3] += origins
root_pose[:, :3] += math_utils.sample_cylinder(
radius=0.1, h_range=(0.25, 0.5), size=cone_object.num_instances, device=cone_object.device
)
# write root state to simulation
cone_object.write_root_pose_to_sim_index(root_pose=root_pose)
root_vel = cone_object.data.default_root_vel.torch.clone()
cone_object.write_root_velocity_to_sim_index(root_velocity=root_vel)
# reset buffers
cone_object.reset()
Stepping the simulation#
Before stepping the simulation, we perform the assets.RigidObject.write_data_to_sim() method. This method
writes other data, such as external forces, into the simulation buffer. In this tutorial, we do not apply any
external forces to the rigid object, so this method is not necessary. However, it is included for completeness.
# apply sim data
cone_object.write_data_to_sim()
Updating the state#
After stepping the simulation, we update the internal buffers of the rigid object prims to reflect their new state
inside the assets.RigidObject.data attribute. This is done using the assets.RigidObject.update() method.
# update buffers
cone_object.update(sim_dt)
The Code Execution#
This script uses OvPhysX and the Newton RTX visualizer without Isaac Sim. Install the ov extra
and run the command below:
uv run --extra ov isaaclab -p scripts/tutorials/01_assets/run_rigid_object.py --viz newton_rtx
This should open a stage with a ground plane, lights, and several green cones. The cones must be dropping from
a random height and settling on to the ground. Press Ctrl+C in the terminal to stop the simulation.
This tutorial showed how to spawn rigid objects and wrap them in a RigidObject class to initialize their
physics handles which allows setting and obtaining their state. In the next tutorial, we will see how to interact
with an articulated object which is a collection of rigid objects connected by joints.