DBMNG数据库管理与应用

科学是实事求是的学问,来不得半点虚假。
当前位置:首页 > 移动应用 > 微信开发

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


本帖最后由 x837195936 于 2018-4-11 18:27 编辑

小程序的加速度计是个很有意思的东西,可以用来做一些手机动作或3D场景。比如手机QQ上的附近的红包活动就是采用加速度计做的。这里写个demo初步做一下加速度计的使用方法。主要步骤:
1、在页面onLoad的时候检测加速度计是否可用。
2、监听加速度计的返回参数(x,y,z)三轴。
3、根据不同的场景去处理数据。

index.wxml
[HTML] 纯文本查看 复制代码
1
2
<!--index.wxml-->
<canvas canvas-id='canvas1' style='width: {{ww}}px;height: {{hh}}px;'></canvas>


index.js
[JavaScript] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
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
[JavaScript] 纯文本查看 复制代码
01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
//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
  }
})


在canvas中绘制了一个小球,根据手机的倾斜小球在屏幕上滚动,碰触到边沿则回弹。
具体效果有兴趣的下载demo自己玩玩吧,过段时间准备拓展一下改成一个小游戏。


  • a.gif (121.48 KB, 下载次数: 5)


    a.gif
本站文章内容,部分来自于互联网,若侵犯了您的权益,请致邮件chuanghui423#sohu.com(请将#换为@)联系,我们会尽快核实后删除。
Copyright © 2006-2023 DBMNG.COM All Rights Reserved. Powered by DEVSOARTECH            豫ICP备11002312号-2

豫公网安备 41010502002439号