-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.js
113 lines (81 loc) · 2.61 KB
/
main.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
window.addEventListener('load', onWindowLoad, false);
function onWindowLoad(){
motionApp();
}
function motionApp(){
if(window.DeviceOrientationEvent){
//browser supports device orientation. add listneer
window.addEventListener('devicemotion', devMotionHandler, false);
}
var tiltLR;
var tiltFB;
var ax;
var ay;
var dir;
var productAngle = 0;
var shipSprite = new Image();
shipSprite.src = 'assets/sprites/ship.png';
var gammaOutput = $('#gammaOutput');
var betaOutput = $('#betaOutput');
var mainCanvas = $('#mainCanvas');
var mainContext = mainCanvas.getContext('2d');
var friction = 0.005;
var ship = {x:425, y:240, velX:0, velY:0, thrust:0.25, width:35, height:28, angle:0, canvasHeight:480, canvasWidth:850};
setInterval(function(){
//draws the canvas with ship
mainContext.fillStyle = '#000';
mainContext.fillRect(0,0,mainCanvas.width, mainCanvas.height);
ship.velX -= ship.velX*friction;
ship.velY -= ship.velY*friction;
ship.x += ship.velX;
ship.y += ship.velY;
checkBoundary(ship);
mainContext.save();
mainContext.translate(ship.x, ship.y);
mainContext.rotate(ship.angle);
mainContext.drawImage(shipSprite, 0-ship.width/2, 0-ship.height/2);
mainContext.restore();
}, 25);
function checkBoundary(object){
if(object.x >= object.canvasWidth+object.width){
object.x = 0;
}else if(object.x <= -object.width){
object.x = object.canvasWidth-object.width;
}else if(object.y >= object.canvasHeight+object.height){
object.y = 0;
}else if(object.y <= -object.height){
object.y = object.canvasHeight-object.height;
}
}
function devMotionHandler(e){
//handles the device orientation event.
tiltLR = e.rotationRate.gamma;
tiltFB = e.rotationRate.beta;
dir = e.rotationRate.alpha;
var futureVelX, futureVelY, futureVel;
ax = (e.accelerationIncludingGravity.x)/5;
ay = (e.accelerationIncludingGravity.y)/5;
var landscapeOrientation = window.innerWidth/window.innerHeight > 1;
if (landscapeOrientation) {
futureVelX = ship.velX-ay;
futureVelY = ship.velY-ax;
} else {
futureVelX = ship.velX+ax;
futureVelY = ship.velY-ay;
}
futureVel = Math.sqrt(futureVelX*futureVelX+futureVelY*futureVelY);
if(futureVel >= 10){
futureVelX = ship.velX;
futureVelY = ship.velY;
}
ship.velX = futureVelX;
ship.velY = futureVelY;
ship.angle = Math.atan2(ship.velY, ship.velX);
gammaOutput.innerHTML = "Device Left/Right Tilt: "+tiltLR;
betaOutput.innerHTML = "Device Front/Back Tilt: "+tiltFB;
}
//end of motion app
function $(selector){
return document.querySelector(selector);
}
}