javascripteaseljstweenjs

Multiple Tweens on One Element


I have a bar that slowly shrinks down via a tween. I'd like to have two buttons controlling the direction of this bar, so that if I hit 'Up' the bar will start climbing back up to it's original form and 'Down' will cause it to start shrinking again.

var bar1Command = bar1.graphics.drawRect(75, 130, 10, 130).command;
var tween1 = createjs.Tween.get(bar1Command, { loop: false, paused: false }).to({ h: 0, y: 260 }, 10000);
var tween2 = createjs.Tween.get(bar1Command, { loop: false, paused: true }).to({h: 130, y: 130}, 10000);

function up() {
  tween1.setPaused(true);
  tween2.setPaused(false);
}

function down() {
  tween1.setPaused(false);
  tween2.setPaused(true);
}

https://jsfiddle.net/rgg8p9k6/

I'm unsure whether it's possible for one tween to affect the state the object was left in by another, since when I hit 'Up' the bar jumps to it's original position.

Thanks for the help!


Solution

  • You can do that by using the override:true option in createjs.Tween.get() to stop the existing tween and replace it with another.

    Also note that because the distance to end point is variable depending on when they change direction, you will need to adjust the duration of the new tween accordingly, to keep the speed constant:

    var duration = 10000;
    
    function up() {
      duration = 10000 * ((130 - bar1Command.h) / 130);
      tween1 = createjs.Tween.get(bar1Command, { loop: false, override:true }).to({ h: 130, y: 130 }, duration);
    }
    
    function down() {
      duration = 10000 * (bar1Command.h / 130);
      tween1 = createjs.Tween.get(bar1Command, { loop: false, override:true }).to({ h: 0, y: 260 }, duration);
    }
    

    Working example: https://jsfiddle.net/pc4rjnLg/1/