How to Tween a variable?

Can someone tell me what I am doing wrong here:

 var from = 0;
 var to = 60;
 var bar = this.bar.element;

this.tween = this.app
        .tween(from)
        .to(to, 2.0, pc.SineOut)
        .loop(false)
        .yoyo(false)
        .on('update', function () {
        bar.width = from;
        console.log(from);
        })
        .start();

“from” logs 90+ times as “0”, why is it not increasing?

Thanks

Figured it out, have to store it in an object.

Hey could you include a code sample of the fix?

Hi @Adrian_Green,

I think the issue with the code snippet above is that you can’t tween numbers directly. You need to create an object to act as holder for any value you are tweening, like this:

1 Like

Hi, I’m still not sure how to use this. I am trying to use the tween as a variable elsewhere (in my case to affect a pose weight) but this code does nothing. How do I access this tween as a variable?

var tween_amount={value:0};
this.app.tween(tween_amount).to({value:1}, 1.0, pc.SineOut).loop(true).start();

meshInstance.morphInstance.setWeight(0, this.tween_amount);

You can use it in the update event callback:

var tween_amount={value:0};

this.app.tween(tween_amount).to({value:1}, 1.0, pc.SineOut)
.on('update', function(){
   meshInstance.morphInstance.setWeight(0, tween_amount.value);
})
.loop(true)
.start();
1 Like

Thanks but when I try to call an external function in the update and pass the value I get an error saying the function is not defined…even though it is.

 var tween_amount={value:0};
    this.app.tween(tween_amount).to({value:1}, 1.0, pc.SineOut)
.on('update', function(){
        console.log(tween_amount.value);
        this.animateBetweenAllPoses(tween_amount.value); //SAYS FUNCTION NOT DEFINED
})
.loop(true)
.start();

Later on I have a function like so…
AnimateMattress.prototype.animateBetweenAllPoses = function(t) {console.log(t);};

It’s a scoping issue. As you are creating an anonymous function, you need to ensure that you are using the correct scope of the this object, variables or binding the function to the correct scope.

.on('update', function(){
        console.log(tween_amount.value);
        this.animateBetweenAllPoses(tween_amount.value); //SAYS FUNCTION NOT DEFINED
}.bind(this))

Worth reading more about it in JS: https://codeburst.io/understanding-that-and-bind-8778f779b149

1 Like

Thanks. i always wondered what that did :slight_smile: