摘要
摇一摇算法网上很多,但都是简单的实现,并不能达到微信摇一摇那种监听动作的准确,为了更好的实现摇一摇,首先需要理解加速计返回数据与摇晃动作的关系,因此介绍一款找加速计数据规律的工具,可直接扫码使用,理解关系后,就很容易实现摇一摇功能。
硬件数据监听工具效果(晃动真机)
扫码体验
体验路径:
摇一摇:硬件系列>摇一摇
硬件数据监听工具:硬件系列>硬件数据监听工具
摇一摇代码
const innerAudioContext = wx.createInnerAudioContext()
Page({
data: {
startTime:0,
x:0,
y:0,
isFirstCallBack:true,
isExecute:false,
isShow: false,
list: [],
shakeTip:''
},
onShow: function () {
innerAudioContext.src = 'https://6e6f-normal-env-ta6pc-1300924598.tcb.qcloud.la/shake.mp3?sign=76981238d10ce97139c6cb7e4c8bd68f&t=1577346589'
var that = this;
that.isShow = true;
wx.onAccelerometerChange(function (e) {
console.log("###",e)
if (!that.isShow) {
return
}
if (that.data.isFirstCallBack) {
that.setData({
startTime: (new Date()).getTime(),
x : e.x,
y : e.y,
isFirstCallBack:false
})
} else {
var endTime = (new Date()).getTime()
var speedX = (e.x - that.data.x) / (endTime - that.data.startTime) * 100000
var speedY = (e.y - that.data.y) / (endTime - that.data.startTime) * 100000
that.setData({
startTime:endTime,
x:e.x,
y:e.y
})
if ((Math.abs(speedX) > 800) || (Math.abs(speedY) > 800)) {
if (that.data.isExecute) {
console.log("正在执行")
} else {
wx.vibrateLong({})
innerAudioContext.play();
that.setData({
isExecute:true,
shakeTip:"摇成功"
})
setTimeout(function () {
that.setData({
isExecute: false,
shakeTip: ""
})
}, 1000)
}
}
}
})
},
onUnload: function () {
this.isShow = false;
wx.stopAccelerometer({})
innerAudioContext.destroy()
}
})
wxml
<view class="container">
<view class="view-row" style="color:#aaa;font-size:36rpx;margin:30rpx;border-bottom:1rpx solid #aaa;padding:10rpx">hardware—摇一摇</view>
<view style="font-size:32rpx;color:#aaa">加速计实现</view>
<image style="width:240rpx;height:240rpx;margin-top:50rpx" src="./shake.png"></image>
<view style="margin-top:30rpx;font-size:40rpx;color:black">{{shakeTip}}</view>
</view>
</view>