r3-legacy/src/game-lib-component-path-fol...

88 lines
2.5 KiB
JavaScript

/**
*
* @param id
* @param name
* @param splineCurve3
* @constructor
*/
GameLib.D3.ComponentPathFollowing = function ComponentPathFollowing(
id,
name,
splineCurve3
) {
this.id = id || GameLib.D3.Tools.RandomId();
if (typeof name == 'undefined') {
name = this.constructor.name;
}
this.name = name;
this.parentEntity = null;
this.splineCurve3 = splineCurve3;
this.currentPathValue = 0.0;
GameLib.D3.Utils.Extend(GameLib.D3.ComponentPathFollowing, GameLib.D3.ComponentInterface);
};
///////////////////////// Methods to override //////////////////////////
GameLib.D3.ComponentPathFollowing.prototype.onUpdate = function(
deltaTime,
parentEntity
) {
if(this.splineCurve3) {
if(this.currentPathValue >= 1) {
this.currentPathValue = 0;
}
//To maintain a constant speed, you use .getPointAt( t ) instead of .getPoint( t ).
//http://stackoverflow.com/questions/18400667/three-js-object-following-a-spline-path-rotation-tanget-issues-constant-sp
var position = this.splineCurve3.getPointAt(this.currentPathValue); //getPointAt?????
var rotation = this.splineCurve3.getTangentAt(this.currentPathValue).normalize();
var up = new THREE.Vector3( 0, 1, 0 );
var axis = new THREE.Vector3();
axis.crossVectors(up, rotation).normalize();
var radians = Math.acos(up.dot(rotation));
var quaternion = new THREE.Quaternion().setFromAxisAngle( axis, radians );
/* var quaternion = new THREE.Quaternion().setFromEuler(
new THREE.Euler(
rotation.x,
rotation.y,
rotation.z
)
);*/
var offset = new THREE.Vector3(1, 0, 0);
offset = offset.applyQuaternion(quaternion).multiplyScalar(10.0);
console.log("offset x", offset);
// apply to parent rigidbody instead of direclty to the mesh.
parentEntity.position.x = position.x + offset.x;
parentEntity.position.y = position.y + offset.y;
parentEntity.position.z = position.z + offset.z;
parentEntity.quaternion.x = quaternion.x;
parentEntity.quaternion.y = quaternion.y;
parentEntity.quaternion.z = quaternion.z;
parentEntity.quaternion.w = quaternion.w;
this.currentPathValue += (0.5 * deltaTime);
}
};
GameLib.D3.ComponentPathFollowing.prototype.onSetParentEntity = function(
parentScene,
parentEntity
) {
if(!this.splineCurve3) {
console.error("NO PATH GIVEN");
}
};