Skip to content

Tween.js

Created: 2018-10-10 11:00:15 -0700 Modified: 2018-10-10 11:05:29 -0700

This is a library for controlling basic tweening of numeric values. It doesn’t tween colors.

Tips I learned after using this library:

  • import * as TWEEN from ‘@tweenjs/tween.js’;
  • Don’t call “start()” on a tween unless you’re going to be updating it immediately thereafter. The reason why is because the library has a built-in “delay()” function that you can chain for if you wanted a delay. When I had an external delay between start() and update(), it jumped my tween immediately to the end since the tween wasn’t aware of the external delay.
  • Functions can all be chained, so you can write code like this:
const tween = new TWEEN.Tween({ alpha: 0 })
.to({ alpha: 1 }, 1000)
.easing(TWEEN.Easing.Sinusoidal.In)
.onUpdate(({alpha}) => {
graphics.alpha = alpha;
})
.start();
  • When updating a tween, you should probably just update all tweens, so you can use TWEEN.update() for that (notice the capital letters). This will update all tweens that you’ve added to the default group (which is what’s exported by default). If you want new groups, the Group function is exported as well as TWEEN.Group.
  • Stopping a tween only removes it from the group that it’s in if it was already playing. Because of this, I wrote this function:
/**
* Calling stop() on an already-stopped tween won't remove it from the Tween
* manager, so this function will handle the case where it's already-stopped by
* starting it again. We COULD just access _group to directly remove the Tween,
* but that's a private variable, so I'd rather use public functions. We could
* also call TWEEN.remove on the specific tween, but if there's ever a different
* group that the tween belongs to, then that wouldn't work. TWEEN.removeAll
* also exists, but not only does that suffer from the same grouping problem as
* TWEEN.remove, but it removes tweens even outside of this class.
* @param {TWEEN.Tween} tween
*/
function stopAndRemoveTween(tween) {
if (!tween.isPlaying()) {
tween.start();
}
tween.stop();
}