PositionInterpolator.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. /**
  2. * @author Bart McLeod, [email protected]
  3. * @since May 25, 2016
  4. *
  5. * Adds animation and interaction support to the VrmlParser.Renderer.ThreeJs
  6. * @todo: take time into account
  7. */
  8. // we use below notation to create exports for the Google closure compiler
  9. /**
  10. * The OrientationInterpolator wraps the essential properties of its original VRML node counterpart
  11. * and adds functionality to support animation in Three.js.
  12. *
  13. * @param originalNode
  14. * @constructor
  15. */
  16. VrmlParser.Renderer.ThreeJs.Animation['PositionInterpolator'] = function (originalNode, debug) {
  17. this.key = originalNode.key;
  18. this.keyValue = originalNode.keyValue;
  19. this.debug = debug ? true : false;
  20. }
  21. VrmlParser.Renderer.ThreeJs.Animation.PositionInterpolator.prototype = {
  22. /**
  23. * Utility to easily switch logging on and off with the debug flag.
  24. * @param obj
  25. */
  26. log: function (obj) {
  27. if ( this.debug ) {
  28. console.log(obj);
  29. }
  30. },
  31. tween: function (target, endPosition) {
  32. return new TWEEN
  33. .Tween(target.position)
  34. .to(endPosition)
  35. .start(+new Date())
  36. ;
  37. },
  38. /**
  39. * Gets the animation callback method, which can play the animation associated with this OrientationInterpolator.
  40. * @param Object3D target
  41. * @param callable finish A method that will be called when the callback is ready to be removed
  42. */
  43. getCallback: function (target, finish) {
  44. var scope = this;
  45. // assumption that the first position is the position the target is already at, so we start with the next
  46. var index = 1;
  47. var p = this.getPosition(index);
  48. this.log(p);
  49. this.log(target);
  50. var tween = this.tween(target, p);
  51. tween.onComplete(function () {
  52. // take next key or finish
  53. index++;
  54. if ( index >= scope.keyValue.length ) {
  55. console.log('finish');
  56. // now make the end position of the target exactly the same as p, to correct any rounding errors from tweening
  57. target.position = p;
  58. finish();
  59. return;
  60. }
  61. p = scope.getPosition(index);
  62. scope.log(p);
  63. tween = scope.tween(target, p);
  64. tween.onComplete = this;
  65. });
  66. /**
  67. * The animation callback
  68. *
  69. * @param float delta time difference
  70. * @param callable finish will be called by the callback when it is ready to be removed
  71. */
  72. var callback = function (delta) {
  73. tween.update(+new Date());
  74. };
  75. return callback;
  76. },
  77. getPosition: function (index) {
  78. var v = this.keyValue[index];
  79. return new THREE.Vector3(v.x, v.y, v.z);
  80. }
  81. };