KeyframeTrack.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /**
  2. *
  3. * A Track that returns a keyframe interpolated value.
  4. *
  5. * TODO: Add cubic in addition to linear interpolation.
  6. *
  7. * @author Ben Houston / http://clara.io/
  8. * @author David Sarno / http://lighthaus.us/
  9. */
  10. THREE.KeyframeTrack = function ( name, keys ) {
  11. this.name = name;
  12. this.keys = keys || []; // time in seconds, value as value
  13. // TODO: sort keys via their times
  14. this.keys.sort( function( a, b ) { return a.time < b.time; } );
  15. };
  16. THREE.KeyframeTrack.prototype = {
  17. constructor: THREE.KeyframeTrack,
  18. getAt: function( time ) {
  19. console.log( 'KeyframeTrack[' + this.name + '].getAt( ' + time + ' )' );
  20. if( this.keys.length == 0 ) throw new Error( "no keys in track named " + this.name );
  21. // before the start of the track, return the first key value
  22. if( this.keys[0].time >= time ) {
  23. console.log( ' before: ' + this.keys[0].value );
  24. return this.keys[0].value;
  25. }
  26. // past the end of the track, return the last key value
  27. if( this.keys[ this.keys.length - 1 ].time <= time ) {
  28. console.log( ' after: ' + this.keys[ this.keys.length - 1 ].value );
  29. return this.keys[ this.keys.length - 1 ].value;
  30. }
  31. // interpolate to the required time
  32. for( var i = 1; i < this.keys.length; i ++ ) {
  33. if( time <= this.keys[ i ].time ) {
  34. // linear interpolation to start with
  35. var alpha = ( time - this.keys[ i - 1 ].time ) / ( this.keys[ i ].time - this.keys[ i - 1 ].time );
  36. var interpolatedValue = THREE.AnimationUtils.lerp( this.keys[ i - 1 ].value, this.keys[ i ].value, alpha );
  37. console.log( ' interpolated: ', {
  38. value: interpolatedValue,
  39. alpha: alpha,
  40. time0: this.keys[ i - 1 ].time,
  41. time1: this.keys[ i ].time,
  42. value0: this.keys[ i - 1 ].value,
  43. value1: this.keys[ i ].value
  44. } );
  45. return interpolatedValue;
  46. }
  47. }
  48. throw new Error( "should never get here." );
  49. };
  50. };
粤ICP备19079148号