-
Notifications
You must be signed in to change notification settings - Fork 2
/
accel.js
79 lines (69 loc) · 1.95 KB
/
accel.js
1
2
3
4
5
6
7
8
9
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
75
76
77
78
79
var h = 500,
w = 500;
/* http://paulirish.com/2011/requestanimationframe-for-smart-animating/ */
window.requestAnimFrame = (function () {
return window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.oRequestAnimationFrame ||
window.msRequestAnimationFrame ||
function(/* function */ callback, /* DOMElement */ element) {
window.setTimeout(callback, 1000 / 60);
};
})();
function Ball(options) {
this.x = options.x || 100;
this.y = options.y || 100;
this.vx = options.vx || 0;
this.vy = options.vy || 0;
this.radius = options.radius || 15;
this.color = options.color || "blue";
this.backgroundColor = options.backgroundColor || "white";
}
Ball.prototype.accelerate = function (acc) {
var landscapeOrientation = window.innerWidth / window.innerHeight > 1;
if (landscapeOrientation) {
this.vx += acc.y;
this.vy += acc.x;
} else {
this.vx += acc.x;
this.vy -= acc.y;
}
this.x += this.vx * 0.1;
this.y += this.vy * 0.1;
if (this.x < 0 + this.radius) {
this.x = 0 + this.radius;
this.vx = -this.vx * 0.8;
}
if (this.y < 0 + this.radius) {
this.y = 0 + this.radius;
this.vy = -this.vy * 0.8;
}
if (this.x > h - this.radius) {
this.x = h - this.radius;
this.vx = -this.vx * 0.8;
}
if (this.y > w - this.radius) {
this.y = w - this.radius;
this.vy = -this.vy * 0.8;
}
};
Ball.prototype.draw = function (context) {
context.fillStyle = this.backgroundColor;
context.fillRect(0, 0, w, h);
context.fillStyle = this.color;
context.beginPath();
context.arc(this.x, this.y, this.radius, 0, Math.PI * 2);
context.closePath();
context.fill();
};
var canvas = document.getElementById("field");
var context = canvas.getContext("2d");
var ball = new Ball({x: 100, y: 100, radius: 15});
window.ondevicemotion = function (e) {
ball.accelerate(e.accelerationIncludingGravity);
};
(function loop() {
ball.draw(context);
requestAnimFrame(loop);
})();