forked from c-frame/aframe-extras
-
Notifications
You must be signed in to change notification settings - Fork 0
/
touch-controls.js
71 lines (57 loc) · 1.59 KB
/
touch-controls.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
/**
* Touch-to-move-forward controls for mobile.
*/
module.exports = AFRAME.registerComponent('touch-controls', {
schema: {
enabled: { default: true }
},
init: function () {
this.dVelocity = new THREE.Vector3();
this.bindMethods();
},
play: function () {
this.addEventListeners();
},
pause: function () {
this.removeEventListeners();
this.dVelocity.set(0, 0, 0);
},
remove: function () {
this.pause();
},
addEventListeners: function () {
const sceneEl = this.el.sceneEl;
const canvasEl = sceneEl.canvas;
if (!canvasEl) {
sceneEl.addEventListener('render-target-loaded', this.addEventListeners.bind(this));
return;
}
canvasEl.addEventListener('touchstart', this.onTouchStart);
canvasEl.addEventListener('touchend', this.onTouchEnd);
},
removeEventListeners: function () {
const canvasEl = this.el.sceneEl && this.el.sceneEl.canvas;
if (!canvasEl) { return; }
canvasEl.removeEventListener('touchstart', this.onTouchStart);
canvasEl.removeEventListener('touchend', this.onTouchEnd);
},
isVelocityActive: function () {
return this.data.enabled && this.isMoving;
},
getVelocityDelta: function () {
this.dVelocity.z = this.isMoving ? -1 : 0;
return this.dVelocity.clone();
},
bindMethods: function () {
this.onTouchStart = this.onTouchStart.bind(this);
this.onTouchEnd = this.onTouchEnd.bind(this);
},
onTouchStart: function (e) {
this.isMoving = true;
e.preventDefault();
},
onTouchEnd: function (e) {
this.isMoving = false;
e.preventDefault();
}
});