touch_sensor/
touch_sensor.rs

1//! Example of using sensor interaction: touch sensor.
2use std::time::Duration;
3
4use mujoco_rs::viewer::MjViewer;
5use mujoco_rs::prelude::*;
6
7
8const EXAMPLE_MODEL: &str = "
9<mujoco>
10    <worldbody>
11        <light ambient=\"0.2 0.2 0.2\"/>
12        <body name=\"ball\">
13            <geom name=\"green_sphere\" size=\".1\" rgba=\"0 1 0 1\" mass=\"1\"/>
14            <joint type=\"free\"/>
15            <site name=\"touch\" size=\".1 .1 .1\" pos=\"0 0 0\" rgba=\"0 1 0 0.2\" type=\"box\"/>
16        </body>
17
18        <body>
19            <geom type=\"box\" size=\"1 1 1\" pos=\"2 1 1\" rgba=\"0 1 1 1\"/>
20            <joint type=\"free\"/>
21        </body>
22
23        <geom name=\"floor\" type=\"plane\" size=\"10 10 1\"/>
24    </worldbody>
25
26    <sensor>
27        <touch name=\"touch\" site=\"touch\"/>
28    </sensor>
29</mujoco>
30";
31
32fn main() {
33    /* Load the model and create data */
34    let model = MjModel::from_xml_string(EXAMPLE_MODEL).expect("could not load the model");
35    let mut data = model.make_data();  // or MjData::new(&model);
36
37    /* Launch a passive Rust-native viewer */
38    let mut viewer = MjViewer::launch_passive(&model, 0)
39        .expect("could not launch the viewer");
40
41    let sensor_data_info = data.sensor("touch").unwrap();
42    while viewer.running() {
43        /* Step the simulation and sync the viewer */
44        viewer.sync(&mut data);
45        data.step();
46
47        /* Print the touch sensor output, which is the contact force */
48        println!("{}", sensor_data_info.view(&data).data[0]);
49
50        std::thread::sleep(Duration::from_secs_f64(0.002));
51    }
52}