Ray Caster#
A ray caster reports the first collision along each ray in a chosen pattern. Rays do not bounce or respond to materials and opacity. Quadruped tasks use this sensor to measure terrain height around the robot.
The single-mesh RayCaster implementation depends on the physics
backend. With PhysX and OV PhysX, configured meshes are loaded into Warp
when the sensor initializes and must remain static. With Newton, the sensor
queries the live scene BVH and therefore sees every collision shape in its
environment, global terrain, and dynamic bodies. Newton ignores
mesh_prim_paths; use
isaaclab_newton.sensors.NewtonRaycastSensorCfg to make that behavior
explicit and to access Newton-specific options.
For explicitly selected moving geometry, MultiMeshRayCaster and
MultiMeshRayCasterCamera load their target meshes once and bind
each tracked mesh to its owning rigid body during initialization. They read live
body poses through the shared scene-data provider, including when several meshes
belong to the same body. Targets with track_mesh_transforms=False retain their
initial poses. The deprecated Newton multi-mesh adapters use this same path;
Newton’s native ray-cast sensor continues to use its scene BVH.
Choose a ray pattern and a parent frame. The frame and sensor offset set the pose; the pattern sets the ray origins and directions. Built-in patterns include lidar and grids.
@configclass
class RaycasterSensorSceneCfg(InteractiveSceneCfg):
"""Design the scene with sensors on the robot."""
# ground plane
ground = AssetBaseCfg(
prim_path="/World/Ground",
spawn=sim_utils.UsdFileCfg(
usd_path=f"{ISAAC_NUCLEUS_DIR}/Environments/Terrains/rough_plane.usd",
scale=(1, 1, 1),
),
)
# lights
dome_light = AssetBaseCfg(
prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75))
)
# robot
robot = replace(ANYMAL_C_CFG, prim_path="{ENV_REGEX_NS}/Robot")
ray_caster = RayCasterCfg(
prim_path="{ENV_REGEX_NS}/Robot/base",
update_period=1 / 60,
offset=RayCasterCfg.OffsetCfg(pos=(0, 0, 0.5)),
mesh_prim_paths=["/World/Ground"],
ray_alignment="yaw",
pattern_cfg=patterns.LidarPatternCfg(
channels=100, vertical_fov_range=[-90, 90], horizontal_fov_range=[-90, 90], horizontal_res=1.0
),
debug_vis=bool(args_cli.visualizer),
)
Pattern angles use degrees. Enable debug visualization to inspect the pattern, then disable it when measuring performance.
Read hit positions from data.ray_hits_w during simulation:
def run_simulator(sim: sim_utils.SimulationContext, scene: InteractiveScene):
.
.
.
# Simulate physics
while sim.is_running():
.
.
.
# print information from the sensors
print("-------------------------------")
print(scene["ray_caster"])
print("Ray cast hit results: ", scene["ray_caster"].data.ray_hits_w)
-------------------------------
Ray-caster @ '/World/envs/env_.*/Robot/base/lidar_cage':
view type : <class 'isaacsim.core.experimental.prims.xform_prim.XformPrim'>
update period (s) : 0.016666666666666666
number of meshes : 1
number of sensors : 1
number of rays/sensor: 18000
total number of rays : 18000
Ray cast hit results: tensor([[[-0.3698, 0.0357, 0.0000],
[-0.3698, 0.0357, 0.0000],
[-0.3698, 0.0357, 0.0000],
...,
[ inf, inf, inf],
[ inf, inf, inf],
[ inf, inf, inf]]], device='cuda:0')
-------------------------------
Hit positions have shape (N, B, 3), where N is the number of sensors and
B is the number of rays. Missed rays return inf. The repeated points in
this example come from rays at the bottom pole of the hemispherical lidar
pattern: all 180 horizontal samples meet there.
Try different patterns in the example below to inspect their hit positions.
Code for raycaster_sensor.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"""Cast a lidar-style ray pattern against rough terrain."""
7
8import argparse
9from types import SimpleNamespace
10from typing import TYPE_CHECKING
11
12import torch
13
14import isaaclab.sim as sim_utils
15from isaaclab.app import add_launcher_args, launch_simulation
16from isaaclab.assets import AssetBaseCfg
17from isaaclab.scene import InteractiveSceneCfg
18from isaaclab.sensors.ray_caster import RayCasterCfg, patterns
19from isaaclab.utils import configclass, instantiate, replace
20from isaaclab.utils.assets import ISAAC_NUCLEUS_DIR
21
22from isaaclab_assets.robots.anymal import ANYMAL_C_CFG
23
24if TYPE_CHECKING:
25 from isaaclab.scene import InteractiveScene
26
27parser = argparse.ArgumentParser(description="Example on using the raycaster sensor.")
28parser.add_argument("--num_envs", type=int, default=1, help="Number of environments to spawn.")
29parser.add_argument("--log_interval", type=int, default=100, help="Steps between compact sensor summaries.")
30parser.add_argument("--max_steps", type=int, default=-1, help="Stop after this many steps; negative runs forever.")
31parser.add_argument(
32 "--physics",
33 default="ovphysx",
34 choices=["isaacsim_physx", "ovphysx"],
35 help="Physics backend.",
36)
37add_launcher_args(parser)
38args_cli = parser.parse_args()
39if args_cli.visualizer is None:
40 args_cli.visualizer = ["newton_gl" if args_cli.physics == "isaacsim_physx" else "newton_rtx"]
41if args_cli.log_interval < 1:
42 parser.error("--log_interval must be at least 1.")
43if args_cli.max_steps == 0 or args_cli.max_steps < -1:
44 parser.error("--max_steps must be positive or -1.")
45
46
47@configclass
48class RaycasterSensorSceneCfg(InteractiveSceneCfg):
49 """Design the scene with sensors on the robot."""
50
51 # ground plane
52 ground = AssetBaseCfg(
53 prim_path="/World/Ground",
54 spawn=sim_utils.UsdFileCfg(
55 usd_path=f"{ISAAC_NUCLEUS_DIR}/Environments/Terrains/rough_plane.usd",
56 scale=(1, 1, 1),
57 ),
58 )
59
60 # lights
61 dome_light = AssetBaseCfg(
62 prim_path="/World/Light", spawn=sim_utils.DomeLightCfg(intensity=3000.0, color=(0.75, 0.75, 0.75))
63 )
64
65 # robot
66 robot = replace(ANYMAL_C_CFG, prim_path="{ENV_REGEX_NS}/Robot")
67
68 ray_caster = RayCasterCfg(
69 prim_path="{ENV_REGEX_NS}/Robot/base",
70 update_period=1 / 60,
71 offset=RayCasterCfg.OffsetCfg(pos=(0, 0, 0.5)),
72 mesh_prim_paths=["/World/Ground"],
73 ray_alignment="yaw",
74 pattern_cfg=patterns.LidarPatternCfg(
75 channels=100, vertical_fov_range=[-90, 90], horizontal_fov_range=[-90, 90], horizontal_res=1.0
76 ),
77 debug_vis=bool(args_cli.visualizer),
78 )
79
80
81def run_simulator(sim: sim_utils.SimulationContext, scene: "InteractiveScene") -> None:
82 """Run the simulator."""
83 # Define simulation stepping
84 sim_dt = sim.get_physics_dt()
85 count = 0
86
87 while sim.is_running() and (args_cli.max_steps < 0 or count < args_cli.max_steps):
88 if count % 500 == 0:
89 # reset the scene entities
90 # root state
91 # we offset the root state by the origin since the states are written in simulation world frame
92 # if this is not done, then the robots will be spawned at the (0, 0, 0) of the simulation world
93 root_pose = scene["robot"].data.default_root_pose.torch.clone()
94 root_pose[:, :3] += scene.env_origins
95 scene["robot"].write_root_pose_to_sim_index(root_pose=root_pose)
96 root_vel = scene["robot"].data.default_root_vel.torch.clone()
97 scene["robot"].write_root_velocity_to_sim_index(root_velocity=root_vel)
98 # set joint positions with some noise
99 joint_pos, joint_vel = (
100 scene["robot"].data.default_joint_pos.torch.clone(),
101 scene["robot"].data.default_joint_vel.torch.clone(),
102 )
103 joint_pos += torch.rand_like(joint_pos) * 0.1
104 scene["robot"].write_joint_position_to_sim_index(position=joint_pos)
105 scene["robot"].write_joint_velocity_to_sim_index(velocity=joint_vel)
106 # clear internal buffers
107 scene.reset()
108 print("[INFO]: Resetting robot state...")
109 targets = scene["robot"].data.default_joint_pos.torch
110 scene["robot"].set_joint_position_target_index(target=targets)
111 scene.write_data_to_sim()
112 sim.step()
113 count += 1
114 scene.update(sim_dt)
115
116 if count % args_cli.log_interval == 0:
117 hits = scene["ray_caster"].data.ray_hits_w.torch
118 valid = torch.isfinite(hits).all(dim=-1)
119 print(f"[INFO] step={count} ray hit rate={valid.float().mean().item():.1%}")
120
121
122def main() -> None:
123 """Run the ray-caster example."""
124 sim_cfg = sim_utils.SimulationCfg(dt=0.005, device=args_cli.device)
125 scene_cfg = RaycasterSensorSceneCfg(num_envs=args_cli.num_envs, env_spacing=2.0)
126 with launch_simulation(SimpleNamespace(sim=sim_cfg, scene=scene_cfg), args_cli):
127 sim = sim_utils.SimulationContext(sim_cfg)
128 sim.set_camera_view(eye=[3.5, 3.5, 3.5], target=[0.0, 0.0, 0.0])
129 scene: InteractiveScene = instantiate(scene_cfg)
130 sim.reset()
131 print("[INFO]: Setup complete...")
132 run_simulator(sim, scene)
133
134
135if __name__ == "__main__":
136 main()