GameLib.D3.ComponentLookAt = function( componentId, targetEntity, targetOffset, rotationSpeed ) { 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.ComponentLookAt, GameLib.D3.ComponentInterface); // todo: USE TARGET OFFSET. this.targetEntity = targetEntity; if(GameLib.D3.Utils.UndefinedOrNull(targetOffset)) { targetOffset = new GameLib.D3.Vector3(0, 0, 0); } this.targetOffset = targetOffset; this.lastTargetQuaternion = new GameLib.D3.Vector4(0, 0, 0, 1); this.rotationSpeed = rotationSpeed || 22.0; }; ComponentLookAt_currentPos = new THREE.Vector3(); ComponentLookAt_targetPos = new THREE.Vector3(); ComponentLookAt_upVector = new THREE.Vector3(0, 1, 0); ComponentLookAt_parentQuaternion = new THREE.Quaternion(0, 0, 0, 1); ComponentLookAt_tmpQuaternion = new THREE.Quaternion(0, 0, 0, 1); ComponentLookAt_newRotationQuaternion = new THREE.Quaternion(0, 0, 0, 1); ComponentLookAt_lastRotationQuaternion = new THREE.Quaternion(0, 0, 0, 1); ComponentLookAt_lookAtMatrix = new THREE.Matrix4(); ///////////////////////// Methods to override ////////////////////////// GameLib.D3.ComponentLookAt.prototype.onUpdate = function( deltaTime, parentEntity ) { if(this.targetEntity) { var target = this.targetEntity.position; ComponentLookAt_currentPos.set( parentEntity.position.x, parentEntity.position.y, parentEntity.position.z ); ComponentLookAt_lastRotationQuaternion.set( this.lastTargetQuaternion.x, this.lastTargetQuaternion.y, this.lastTargetQuaternion.z, this.lastTargetQuaternion.w ); ComponentLookAt_targetPos.set( target.x + this.targetOffset.x, target.y + this.targetOffset.y, target.z + this.targetOffset.z ); ComponentLookAt_lookAtMatrix.lookAt( ComponentLookAt_currentPos, ComponentLookAt_targetPos, ComponentLookAt_upVector ); ComponentLookAt_tmpQuaternion.setFromRotationMatrix(ComponentLookAt_lookAtMatrix); var t = deltaTime * this.rotationSpeed; t = t * t * t * (t * (6.0 * t - 15.0) + 10.0); THREE.Quaternion.slerp(ComponentLookAt_lastRotationQuaternion, ComponentLookAt_tmpQuaternion, ComponentLookAt_newRotationQuaternion, t); this.parentEntity.quaternion.x = this.lastTargetQuaternion.x = ComponentLookAt_newRotationQuaternion.x; this.parentEntity.quaternion.y = this.lastTargetQuaternion.y = ComponentLookAt_newRotationQuaternion.y; this.parentEntity.quaternion.z = this.lastTargetQuaternion.z = ComponentLookAt_newRotationQuaternion.z; this.parentEntity.quaternion.w = this.lastTargetQuaternion.w = ComponentLookAt_newRotationQuaternion.w; } };