KeyframeTrack.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. THREE.KeyframeTrack = function ( name, keys ) {
  2. this.keys = keys || []; // time in seconds, value as value
  3. // TODO: sort keys via their times
  4. this.keys.sort( function( a, b ) { return a.time < b.time; } );
  5. THREE.Track.call( this, name );
  6. };
  7. THREE.KeyframeTrack.prototype = {
  8. constructor: THREE.Track,
  9. getAt: function( time ) {
  10. if( this.keys.length == 0 ) throw new Error( "no keys in track named " + this.name );
  11. // before the start of the track, return the first key value
  12. if( this.keys[0].time >= time ) {
  13. return this.keys[0].value;
  14. }
  15. // past the end of the track, return the last key value
  16. if( this.keys[ this.keys.length - 1 ].time <= time ) {
  17. return this.keys[ this.keys.length - 1 ].value;
  18. }
  19. // interpolate to the required time
  20. for( var i = 1; i < this.keys.length; i ++ ) {
  21. if( time <= this.keys[ i ].time ) {
  22. // linear interpolation to start with
  23. var alpha = ( time - this.keys[ i - 1 ].time ) / ( this.keys[ i ].time - this.keys[ i - 1 ].time );
  24. return THREE.AnimationUtils.lerp( this.keys[ i - 1 ].value, this.keys[ i ].value, alpha );
  25. }
  26. }
  27. throw new Error( "should never get here." );
  28. };
  29. };