r3-legacy/src/game-lib-component-trigger-...

104 lines
3.0 KiB
JavaScript

//
// this component operates on it's parent entity's bounding box.
// so, you can't use this component with a null-mesh.
//
GameLib.D3.ComponentTriggerBoxBox = function ComponentTriggerBoxBox(
id,
name,
entitiesToCheck,
onInside,
onEnter,
onLeave,
onSetParent
) {
console.log('triggerbox box!');
this.id = id || GameLib.D3.Tools.RandomId();
if (typeof name == 'undefined') {
name = this.constructor.name;
}
this.name = name;
this.parentEntity = null;
// Todo: this should be executed somewhere in game-lib-z, so that we don't execute it on every construction of an object.
GameLib.D3.Utils.Extend(GameLib.D3.ComponentTriggerBoxBox, GameLib.D3.ComponentInterface);
this.entitiesToCheck = entitiesToCheck || [];
this.onInside = onInside || null;
this.onEnter = onEnter || null;
this.onLeave = onLeave || null;
this.onSetParent = onSetParent || null;
// defines code
this.entitiesInside = [];
};
//#ifdef RUNTIME__
if(typeof THREE != "undefined") {
ComponentTriggerBoxBox_BB = new THREE.Box3();
ComponentTriggerBoxBox_BBEntity = new THREE.Box3();
}
///////////////////////// Methods to override //////////////////////////
GameLib.D3.ComponentTriggerBoxBox.prototype.onUpdate = function(
deltaTime,
parentEntity
) {
if(parentEntity.mesh) {
// Calculate the current transform here, using the position, orientation and scale of the entity.
ComponentTriggerBoxBox_BB.setFromObject(parentEntity.mesh);
for(var e in this.entitiesToCheck) {
var entityToCheck = this.entitiesToCheck[e];
ComponentTriggerBoxBox_BBEntity.setFromObject(entityToCheck.mesh);
if(ComponentTriggerBoxBox_BB.intersectsBox(ComponentTriggerBoxBox_BBEntity)) {
if(this.entitiesInside.indexOf(entityToCheck) <= -1) { // check if this is the first time the entity enters the trigger
this.entitiesInside.push(entityToCheck);
if(this.onEnter) {
if(this.onEnter(parentEntity, entityToCheck)) {
break;
}
}
}
if(this.onInside) {
if(this.onInside(parentEntity, entityToCheck)) {
break;
}
}
} else if(this.entitiesInside.indexOf(entityToCheck) > -1) { // entity WAS inside the trigger
this.entitiesInside.splice(this.entitiesInside.indexOf(entityToCheck), 1);
if(this.onLeave) {
if(this.onLeave(parentEntity, entityToCheck)) {
break;
}
}
}
}
}
};
//#endif
GameLib.D3.ComponentTriggerBoxBox.prototype.onSetParentEntity = function(
parentScene,
parentEntity
) {
if(this.onSetParent) {
this.onSetParent(parentScene, parentEntity);
}
};