x***@10001wan.com
x***@10001wan.com
  • 发布:2021-03-06 22:28
  • 更新:2021-03-07 20:01
  • 阅读:1358

摇一摇算法,摇一次触发多次的问题

分类:uni-app

代码就是这样子,但是经常摇晃一次,console.warn("达到速度,执行一次==========");这一句就会连续触发2次,这是什么原因,有没有人遇到过?

data() {  
    return {  
        isFirstCallBack:true,  
        // 一些全局变量  
        global: {  
            lastTime: 0, //此变量用来记录上次摇动的时间  
            intervalTime: 800, // 两次摇一摇的间隔事件  
            lastX: 0,  
            lastY: 0,  
            lastZ: 0, //此组变量分别记录对应x、y、z三轴的数值和上次的数值  
            shakeSpeed: 800 //设置阈值  
        },  
    };  
},  
onLoad() {  
    // 监听摇一摇事件  
    uni.onAccelerometerChange(this.onAccelerometerChange);  
},  
onAccelerometerChange(acceleration) {  
    let nowTime = new Date().getTime(); //记录当前时间  
    let self = this;  
    let x = acceleration.x; // 获取x轴数值,x轴为垂直于北轴,向东为正  
    let y = acceleration.y; // 获取y轴数值,y轴向正北为正  
    let z = acceleration.z; // 获取z轴数值,z轴垂直于地面,向上为正  
    //如果是第一次回调,先只记录坐标点  
    if(this.isFirstCallBack){  
        this.global.lastX = x;  
        this.global.lastY = y;  
        this.global.lastZ = z;  
        this.isFirstCallBack = false;  
        return;  
    }  
    //如果这次摇的时间距离上次摇的时间有一定间隔 才执行  
    if ((nowTime - this.global.lastTime) > this.global.intervalTime) {  
        // console.log('时间间隔允许')  
        let diffTime = nowTime - this.global.lastTime; //记录时间段  
        this.global.lastTime = nowTime; // 记录本次摇动时间,为下次计算摇动时间做准备  
        let speed = Math.abs( x + y + z - self.global.lastX - self.global.lastY - self.global.lastZ) / diffTime * 100000  
        //如果计算出来的速度超过了阈值,那么就算作用户成功摇一摇  
        if ((speed > this.global.shakeSpeed) && !this.isShark) {  
            console.warn("达到速度,执行一次==========");  
            uni.stopAccelerometer();  
            this.isShark = true;  

            setTimeout(()=>{  
                uni.startAccelerometer();  
                this.isShark = false;  
            },1000);  
        }  
        //赋值,为下一次计算做准备  
        this.global.lastX = x;  
        this.global.lastY = y;  
        this.global.lastZ = z;  
    }  
}
2021-03-06 22:28 负责人:无 分享
已邀请:
x***@10001wan.com

x***@10001wan.com (作者)

....

x***@10001wan.com

x***@10001wan.com (作者)

....

该问题目前已经被锁定, 无法添加新回复