uniapp重力感应
uniapp 实现重力感应的方法
uniapp 中可以通过调用设备的加速度计 API 实现重力感应功能。主要依赖 uni.onAccelerometerChange 和 uni.startAccelerometer 等 API。
启用加速度计监听

uni.startAccelerometer({
interval: 'game',
success: function () {
console.log('加速度计监听已开启');
},
fail: function (err) {
console.log('开启失败:', err);
}
});
监听加速度变化
uni.onAccelerometerChange(function (res) {
console.log('X轴加速度:', res.x);
console.log('Y轴加速度:', res.y);
console.log('Z轴加速度:', res.z);
});
处理重力感应数据
获取到的加速度数据可以用于控制界面元素移动或游戏角色行为。通常需要对原始数据进行处理:

// 示例:根据X轴倾斜控制元素移动
let speed = 5; // 移动速度系数
uni.onAccelerometerChange(function (res) {
let moveX = res.x * speed;
// 更新界面元素位置
this.setData({
positionX: this.data.positionX + moveX
});
});
停止监听
使用完毕后应当停止监听以节省资源:
uni.stopAccelerometer({
success: function () {
console.log('已停止加速度计监听');
}
});
注意事项
- 部分低端设备可能不支持加速度计
- iOS和Android设备返回的数值范围可能不同
- 需要在小程序或App环境中使用,H5环境不支持
- 频繁更新界面可能导致性能问题,建议适当节流
兼容性处理
检测设备是否支持加速度计功能:
uni.getSystemInfo({
success: function (res) {
if (res.platform === 'ios' || res.platform === 'android') {
console.log('当前设备支持加速度计');
} else {
console.log('当前设备不支持加速度计');
}
}
});

