前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >小程序重力感应-加速度计的使用

小程序重力感应-加速度计的使用

作者头像
极乐君
发布2018-07-05 15:39:16
1.3K0
发布2018-07-05 15:39:16
举报
文章被收录于专栏:极乐技术社区极乐技术社区

小程序的加速度计是个很有意思的东西,可以用来做一些手机动作或3D场景。比如手机QQ上的附近的红包活动就是采用加速度计做的。这里写个demo初步做一下加速度计的使用方法。

主要步骤: 1、在页面onLoad的时候检测加速度计是否可用。 2、监听加速度计的返回参数(x,y,z)三轴。 3、根据不同的场景去处理数据。

index.wxml

<canvas canvas-id='canvas1' style='width: {{ww}}px;height: {{hh}}px;'>

</canvas>

index.js

const app = getApp()

const ctx = wx.createCanvasContext('canvas1')

const ww = app.globalData.ww

const hh = app.globalData.hh

Page({

data: {

ww: ww,

hh: hh

},

onLoad() {

var that = this;

wx.startAccelerometer({

success(res) {

that.start()

}

});

this.hf_w = ww / 2;

this.hf_h = hh / 2;

this.x = 0;

this.y = 0;

this.ax = 0;

this.ay = 0;

this.vx = 0;

this.vy = 0;

this.draw();

},

start() {

var vt = 5, that = this;

wx.onAccelerometerChange(function (res) {

that.ax = res.x * vt;

that.ay = res.y * vt;

});

setInterval(function () {

var lo = ww / hh > 1;

if (lo) {

that.vx = that.vx + that.ay;

that.vy = that.vy + that.ax;

} else {

that.vy = that.vy - that.ay;

that.vx = that.vx + that.ax;

}

that.vx = that.vx * 0.98;

that.vy = that.vy * 0.98;

that.y = parseInt(that.y + that.vy / 50);

that.x = parseInt(that.x + that.vx / 50);

that.boundingBoxCheck();

that.draw();

}, 100 / 6)

},

end() {

wx.stopAccelerometer()

},

draw() {

console.log(this.x);

ctx.clearRect(0, 0, ww, hh);

ctx.fillRect(0, 0, ww, hh)

ctx.fill()

ctx.beginPath();

ctx.arc(this.x, this.y, 20, 0, Math.PI * 2);

ctx.setFillStyle('#FFFFFF');

ctx.fill()

ctx.draw();

},

boundingBoxCheck() {

if (this.x < 0) { this.x = 0; this.vx = -this.vx; }

if (this.y < 0) { this.y = 0; this.vy = -this.vy; }

if (this.x > ww - 20) { this.x = ww - 20; this.vx = -this.vx; }

if (this.y > hh - 20) { this.y = hh - 20; this.vy = -this.vy; }

}

})

app.js

//app.js

App({

onLaunch: function () {

var that = this;

wx.getSystemInfo({

success(res) {

that.globalData.ww = res.windowWidth;

that.globalData.hh = res.windowHeight;

}

})

},

globalData: {

userInfo: null

}

})

小程序社区版主 x837195936(熊晨沣):在canvas中绘制了一个小球,根据手机的倾斜小球在屏幕上滚动,碰触到边沿则回弹。具体效果有兴趣的下载demo自己玩玩吧(点击原文即可获取下载地址),过段时间准备拓展一下改成一个小游戏。

本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-04-24,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 极乐技术社区 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
相关产品与服务
云开发 CloudBase
云开发(Tencent CloudBase,TCB)是腾讯云提供的云原生一体化开发环境和工具平台,为200万+企业和开发者提供高可用、自动弹性扩缩的后端云服务,可用于云端一体化开发多种端应用(小程序、公众号、Web 应用等),避免了应用开发过程中繁琐的服务器搭建及运维,开发者可以专注于业务逻辑的实现,开发门槛更低,效率更高。
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档