加速度计

基础库 swan-game.js 1.5.2 版本开始支持。

swan.onAccelerometerChange()

监听加速度数据,频率:5 次/秒,接口调用后会自动开始监听,可使用 swan.stopAccelerometer 停止监听。

swan.onAccelerometerChange(callback)

callback 回调参数:

属性 类型 描述
x number X 轴
y number Y 轴
z number Z 轴

示例:

swan.onAccelerometerChange(function (res) {
    console.log(res.x);
    console.log(res.y);
    console.log(res.z);
});

swan.startAcclerometer()

开始监听加速度数据。

swan.startAcclerometer(opts)

opts 对象属性说明

属性 类型 默认值 是否必填 描述
opts Object 调用该方法时,要传入的对象参数
opts.interval string 监听加速度数据回调函数的执行频率
opts.success function 接口调用成功的回调函数
opts.fail function 接口调用失败的回调函数
opts.complete function 接口调用完成的回调函数(接口成功、失败都会执行)

interval 的有效值

根据机型性能、当前 CPU 与内存的占用情况,interval 的设置与实际 swan.onAccelerometerChange() 回调函数的执行频率会有一些出入。

说明
game 适用于更新游戏的回调频率,在 20 ms/次左右
ui 适用于更新 UI 的回调频率,在 60 ms/次左右
normal 普通的回调频率,在 200 ms/次左右

示例:

swan.startAccelerometer({
    interval: 'ui',
    success: res => {
        console.log(res);
    }
});

swan.stopAccelerometer()

停止监听加速度数据。

swan.stopAccelerometer(opts)

opts 对象属性说明

属性 类型 默认值 是否必填 描述
opts Object 调用该方法时,要传入的对象参数
opts.success function 接口调用成功的回调函数
opts.fail function 接口调用失败的回调函数
opts.complete function 接口调用完成的回调函数(接口成功、失败都会执行)

示例:

swan.stopAccelerometer({
    success: res => {
        console.log(res);
    }
});