有时候我们在用cocos creator调用微信api接口的时候会发现,如果根据官方的例子来写例子的话是这个样子的
wx.startAccelerometer()
wx.onAccelerometerChange(function (res) {
if(res.x >1.5 || res.y>1.5 || res.z>1.5 ){
//判断手机是否摇动
}
})
然后在结束的时候写一个
onDestroy(){
if(typeof(wx) != "undefined"){
console.log("停止监听加速器");
wx.stopAccelerometer();
}
},
大概这个玩意
但是对于新手来说这样写问题很大,具体在于wx.onAccelerometerChange(function (res) 这个方法当中,你每次往里面塞一个判断相当于注册了多次这类型的函数,会导致后面某些关卡不执行相对应的判断也会调用这个函数里面的功能,那么怎么解决这些并且写一个完善的方法来调用加速器api呢
代码段如下
window.shake = {
callBack: null,
init: function () {
console.log(this);
if(typeof(wx) != 'undefined'){
let self = this;
wx.startAccelerometer();
wx.onAccelerometerChange(function(res){
console.log("加速计回调");
if(self.callBack){
self.callBack(res);
}
})
}
},
start: function (call) {
this.callBack = call;
if(typeof(wx) != 'undefined'){
wx.startAccelerometer();
}
},
stop: function () {
this.callBack = null;
if(typeof(wx) != 'undefined'){
wx.stopAccelerometer();
}
}
};
这相当与一个总的方法,在一开始就可以写入段代码并且在这个脚本内的start{}里面加上
window.shake.init();
好了,接下来的使用方法其实就是将一开始的功能修改之后就好了
window.shake.start(function (res) {
if(res.x >1.5 || res.y>1.5 || res.z>1.5 ){
//判断手机是否摇动
}
})
在结束的onDestroy方法就变成这样子了
window.shake.stop();
如此一来便不会存在微信加速度重复注册的问题了