Skip to content

Instantly share code, notes, and snippets.

@vincent
Last active February 1, 2019 18:30
Show Gist options
  • Save vincent/4ce2f9f37b1ac846f84c to your computer and use it in GitHub Desktop.
Save vincent/4ce2f9f37b1ac846f84c to your computer and use it in GitHub Desktop.
Move a Three.js object along a path, or an array of THREE.Vector3
var noop = function(){};
function moveAlong ( object, shape, options ) {
options = _.merge({
from: 0,
to: 1,
duration: null,
speed: 50,
start: true,
yoyo: false,
onStart: null,
onComplete: noop,
onUpdate: noop,
smoothness: 100,
easing: TWEEN.Easing.Linear.None
}, options);
// array of vectors to determine shape
if (shape instanceof THREE.Shape) {
} else if ( shape.constructor === Array ) {
shape = new THREE.SplineCurve3(shape);
} else {
throw '2nd argument is not a Shape, nor an array of vertices';
}
options.duration = options.duration || shape.getLength();
options.length = options.duration * options.speed;
var tween = new TWEEN.Tween({ distance: options.from })
.to({ distance: options.to }, options.length)
.easing( options.easing )
.onStart( options.onStart )
.onComplete( options.onComplete )
.onUpdate(function(){
// get the position data half way along the path
var pathPosition = shape.getPointAt( this.distance );
// move to that position
object.position.set( pathPosition.x, pathPosition.y, pathPosition.z );
object.updateMatrix();
if ( options.onUpdate ) { options.onUpdate( this, shape ); }
})
.yoyo( options.yoyo );
if ( options.yoyo ) {
tween.repeat( Infinity );
}
if ( options.start ) { tween.start(); }
return tween;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment