我正在使用 react-native-sensors 来获取加速度计读数。它正在正确读取传感器值。作为 React Native 的新手,我不知道如何在 sensor.subscribe 方法中添加代码来计算加速度矢量。
import {
setUpdateIntervalForType,
SensorTypes,
accelerometer,
gyroscope
} from 'react-native-sensors';
........
export default class Accelerometer extends Component {
constructor(props) {
super(props);
setUpdateIntervalForType(SensorTypes.accelerometer, 200);
this.accelSubscription = accelerometer.subscribe(({ x, y, z, timestamp }) =>
this.setState({
accel_x: x,
accel_y: y,
accel_z: z,
})
);
this.state = {
acceleration: 0,
accel_x: 0,
accel_y: 0,
accel_z: 0,
};
}
这是每当我获得新的加速度计读数时我想要执行的计算代码:
const accelx = this.state.accel_x;
const accely = this.state.accel_y;
const accelz = this.state.accel_z;
const lastAccel = this.state.acceleration;
const currAcceleration = Math.sqrt((accelx * accelx) + (accely * accely) + (accelz * accelz));
//I need to delta value to detect changes
const accelerationDelta = currAcceleration - lastAccel;
this.setState({
acceleration: currAcceleration,
});
如果我将代码直接放在 accelerometer.subscribe() 中,它会抛出错误。我怎样才能做到这一点?