-
Notifications
You must be signed in to change notification settings - Fork 0
/
grab.js
86 lines (78 loc) · 2.85 KB
/
grab.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
/* global AFRAME */
/**
* Handles events coming from the hand-controls.
* Determines if the entity is grabbed or released.
* Updates its position to move along the controller.
*/
AFRAME.registerComponent('grab', {
init: function () {
this.GRABBED_STATE = 'grabbed';
// Bind event handlers
this.onHit = this.onHit.bind(this);
this.onGripOpen = this.onGripOpen.bind(this);
this.onGripClose = this.onGripClose.bind(this);
},
play: function () {
var el = this.el;
el.addEventListener('hit', this.onHit);
el.addEventListener('gripclose', this.onGripClose);
el.addEventListener('gripopen', this.onGripOpen);
el.addEventListener('thumbup', this.onGripClose);
el.addEventListener('thumbdown', this.onGripOpen);
el.addEventListener('pointup', this.onGripClose);
el.addEventListener('pointdown', this.onGripOpen);
},
pause: function () {
var el = this.el;
el.removeEventListener('hit', this.onHit);
el.removeEventListener('gripclose', this.onGripClose);
el.removeEventListener('gripopen', this.onGripOpen);
el.removeEventListener('thumbup', this.onGripClose);
el.removeEventListener('thumbdown', this.onGripOpen);
el.removeEventListener('pointup', this.onGripClose);
el.removeEventListener('pointdown', this.onGripOpen);
},
onGripClose: function (evt) {
this.grabbing = true;
delete this.previousPosition;
},
onGripOpen: function (evt) {
var hitEl = this.hitEl;
this.grabbing = false;
if (!hitEl) { return; }
hitEl.removeState(this.GRABBED_STATE);
this.hitEl = undefined;
},
onHit: function (evt) {
var hitEl = evt.detail.el;
// If the element is already grabbed (it could be grabbed by another controller).
// If the hand is not grabbing the element does not stick.
// If we're already grabbing something you can't grab again.
if (!hitEl || hitEl.is(this.GRABBED_STATE) || !this.grabbing || this.hitEl) { return; }
hitEl.addState(this.GRABBED_STATE);
this.hitEl = hitEl;
},
tick: function () {
var hitEl = this.hitEl;
var position;
if (!hitEl) { return; }
this.updateDelta();
position = hitEl.getComputedAttribute('position');
hitEl.setAttribute('position', {
x: position.x + this.deltaPosition.x,
y: position.y + this.deltaPosition.y,
z: position.z + this.deltaPosition.z
});
},
updateDelta: function () {
var currentPosition = this.el.getComputedAttribute('position');
var previousPosition = this.previousPosition || currentPosition;
var deltaPosition = {
x: currentPosition.x - previousPosition.x,
y: currentPosition.y - previousPosition.y,
z: currentPosition.z - previousPosition.z
};
this.previousPosition = currentPosition;
this.deltaPosition = deltaPosition;
}
});