diff --git a/src/game-lib-component-trigger-box-sphere.js b/src/game-lib-component-trigger-box-sphere.js new file mode 100644 index 0000000..8ac3d7f --- /dev/null +++ b/src/game-lib-component-trigger-box-sphere.js @@ -0,0 +1,89 @@ +// +// this component operates on it's parent entity's bounding box. +// so, you can't use this component with a null-mesh. +// +GameLib.D3.ComponentTriggerBoxSphere = function( + componentId, + entitiesToCheck, + callback +) { + this.componentId = componentId || GameLib.D3.Tools.RandomId(); + 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.ComponentTriggerBoxSphere, GameLib.D3.ComponentInterface); + + this.entitiesToCheck = entitiesToCheck || []; + this.callback = callback || null; +}; + +if(typeof THREE != "undefined") { + ComponentTriggerBoxSphere_BoxInverseTransform = new THREE.Matrix4(); + ComponentTriggerBoxSphere_TargetPosition_Vec3 = new THREE.Vector3(); + ComponentTriggerBoxSphere_TargetRadius = 0.0; +} + +///////////////////////// Methods to override ////////////////////////// +GameLib.D3.ComponentTriggerBoxSphere.prototype.onUpdate = function( + deltaTime, + parentEntity +) { + + if(parentEntity.mesh) { + // Calculate the current transform here, using the position, orientation and scale of the entity. + + if(!parentEntity.mesh.geometry.boundingBox) { + parentEntity.mesh.geometry.computeBoundingBox(); + } + + ComponentTriggerBoxSphere_BoxInverseTransform.getInverse(parentEntity.mesh.matrix); + + for(var e in this.entitiesToCheck) { + var entityToCheck = this.entitiesToCheck[e]; + + if(entityToCheck.mesh) { + + if (!entityToCheck.mesh.geometry.boundingSphere) { + entityToCheck.mesh.geometry.computeBoundingSphere(); + } + + var spherePosition = new THREE.Vector3( + entityToCheck.position.x, + entityToCheck.position.y, + entityToCheck.position.z + ); + + spherePosition.applyMatrix4(ComponentTriggerBoxSphere_BoxInverseTransform); + + var sphere = new THREE.Sphere( + spherePosition, + entityToCheck.mesh.geometry.boundingSphere.radius + ); + + if(this.callback && parentEntity.mesh.geometry.boundingBox.intersectsSphere(sphere)) { + this.callback(parentEntity, entityToCheck); + } + + } else { // no target mesh geometry. + + var spherePosition = new THREE.Vector3( + entityToCheck.position.x, + entityToCheck.position.y, + entityToCheck.position.z + ); + + spherePosition.applyMatrix4(ComponentTriggerBoxSphere_BoxInverseTransform); + + var sphere = new THREE.Sphere( + spherePosition, + 1 + ); + + if(this.callback && parentEntity.mesh.geometry.boundingBox.intersectsSphere(sphere)) { + this.callback(parentEntity, entityToCheck); + } + + } + } + } +}; \ No newline at end of file