How to correctly chain tweens?

301 Views Asked by At

I'm trying to create a tween that should interpolate some values sequentially, following a sequence of steps.

For some reasons it seems like all the intermediate steps are lost and only the last one is actually used. For example, given the following piece of code:

var tween = new TWEEN.Tween(start).to(X, 10000).to(Y, 5000);
tween.start();

I'd expect to see the values of object start go to the values in X in ten seconds and then, after this step is completed, reach the values of Y in 5 seconds: total duration 15 seconds. What I see instead is the values going to Y in 5 seconds, as if .to(X, 10000) was never called.

I've read code that chains .to calls, so it seems it should work (e.g. this question) and the first example in the documentation seems to imply this kind of usage.

The actual code I'm using builds a Tween from an array of objects that represent intermediate steps. So the code is more on the line of:

var tween = new TWEEN.Tween(steps[0]);
for (var i=1; i < steps.length; i++)
{
    tween.to(steps[i], timings[i]);
}
tween.onUpdate(callback)
tween.start();

Is the above code correct or am I making some silly mistake? I've noticed that there is a chain method, should I use that instead creating a different tween for each step?


MWE:

<html>
    <head>
        <script src="tween.min.js"></script>
    </head>
    <body>

        <script>
            var start = {x:0};
            var tween = new TWEEN.Tween(start);
            tween.to({x: 10}, 10000);
            tween.to({x: -100}, 10000);
            tween.onUpdate(function () {
                console.log("called");
                start.x = this.x;
            });

            tween.start();

            function check() {
                requestAnimationFrame(check);

                TWEEN.update();
                console.log("start.x = " + start.x);
            }

            check();
        </script>
    </body>
</html>

Notice how the output is:

"start.x = 0.0"
"start.x = -0.24"
"start.x = -0.5599999999999999"
"start.x = -0.6799999999999999"
"start.x = -0.7000000000000001"
   ....
"start.x = -100.0"

While I'd expect it to be something like:

"start.x = 0.0"
"start.x = 0.33"
    ...
"start.x = 10.0"
"start.x = 9.81"
   ...
"start.x = 0.0"
"start.x = -0.24"
"start.x = -0.5599999999999999"
"start.x = -0.6799999999999999"
"start.x = -0.7000000000000001"
   ....
"start.x = -100.0"
1

There are 1 best solutions below

0
On

You can do like this to chain tween

var tweenA = new TWEEN.Tween({x:0})
.tween.to({x: 10}, 10000);
.start();

var tweenB = new TWEEN.Tween({x: 10})
.tween.to({x: -100}, 10000);

tweenA.chain(tweenB);