-
Notifications
You must be signed in to change notification settings - Fork 3
/
aframe-triggerbox-component.js
99 lines (96 loc) · 2.81 KB
/
aframe-triggerbox-component.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
if (typeof AFRAME === 'undefined') {
throw new Error('Component attempted to register before AFRAME was available.');
}
/**
* Trigger box, emit an event on the moving entity once it enters and leaves a predefined area
*
* Usage <camera triggerbox="triggereventname: mytriggerbox" /> will make a 10x10x10 box
* will emits event mytriggerbox_entered once the camera moves in
* and event mytriggerbox_entered once the camera leaves it.
*
* It can also be used on other entity e.g. an enemy or a bonus.
*
* inspired by https://github.com/atomicguy/aframe-fence-component/
*
*/
AFRAME.registerComponent('triggerbox', {
multiple: true,
schema: {
width: {
type: 'number',
default: 1
},
height: {
type: 'number',
default: 1
},
depth: {
type: 'number',
default: 1
},
x0: {
type: 'number',
default: 0
},
y0: {
type: 'number',
default: 0
},
z0: {
type: 'number',
default: 0
},
triggereventname: {
type: 'string',
default: 'triggerbox'
}
},
init: function() {
// we don't know yet where we are
this.lastestateset = false;
this.laststateinthetriggerbox = false;
},
tick: function() {
// gathering all the data
var data = this.data;
var thiswidth = data.width;
var thisheight = data.height;
var thisdepth = data.depth;
var x0 = data.x0;
var y0 = data.y0;
var z0 = data.z0;
var triggereventname = data.triggereventname;
var lastestateset = this.lastestateset;
var laststateinthetriggerbox = this.laststateinthetriggerbox;
//done here assuming the box size and position can change since init
minX = thiswidth / 2 + x0;
maxX = ( -1 * thiswidth / 2 ) + x0;
minY = thisheight / 2 + y0;
maxY = ( -1 * thisheight / 2 ) + y0;
minZ = thisdepth / 2 + z0;
maxZ = ( -1 * thisdepth / 2 ) + z0;
var position = this.el.getAttribute('position');
if (( minX > position.x) && (maxX < position.x)
&& ( minY > position.y) && ( maxY < position.y)
&& ( minZ > position.z) && ( maxZ < position.z)){
// we are in
if (lastestateset){
// we were not before
if (!laststateinthetriggerbox) {
var event = new Event(triggereventname+'_entered'); this.el.dispatchEvent(event);
}
}
this.laststateinthetriggerbox = true;
} else {
// we are out
if (lastestateset){
if (laststateinthetriggerbox) {
// we were not before
var event = new Event(triggereventname+'_exited'); this.el.dispatchEvent(event);
}
}
this.laststateinthetriggerbox = false;
}
this.lastestateset = true;
},
});