Skip to main content
Read a MuJoCo sensor’s value by name. Returns a handle with read() updated every physics frame.

Signature

useSensor(name: Sensors): SensorHandle

Usage

import { useSensor } from "mujoco-react";

function ForceSensorDisplay() {
  const force = useSensor("force_sensor");
  const textRef = useRef<any>(null);

  useFrame(() => {
    const v = force.read();
    const magnitude = Math.sqrt(v[0] ** 2 + v[1] ** 2 + v[2] ** 2);
    if (textRef.current) textRef.current.text = `${magnitude.toFixed(2)} N`;
  });

  return <Text ref={textRef} position={[0, 0.5, 0]} />;
}

Return Value

interface SensorHandle {
  read(): Float64Array;
  dim: number;
  name: Sensors;
}
FieldTypeDescription
read()() => Float64ArrayCurrent sensor reading from data.sensordata
dimnumberNumber of values (e.g., 3 for a force sensor, 1 for a scalar)
nameSensorsSensor name

Sensor Types

Common MuJoCo sensor types and their dimensions:
Sensor TypedimDescription
touch1Contact normal force
accelerometer3Linear acceleration
gyro3Angular velocity
force3Constraint force
torque3Constraint torque
jointpos1Joint position
jointvel1Joint velocity
framepos3Frame position
framequat4Frame orientation

Notes

  • The read() array is updated every frame via useAfterPhysicsStep
  • If the sensor doesn’t exist, read() returns an empty Float64Array
  • For enumerating all sensors, use api.getSensors()
  • The name parameter accepts string by default, or a union type if you’ve declared a Register augmentation