javascriptbabylonjsbabel-babylon

Stopping/Restarting animation inside loop with Babylon.JS


I'm setting this loop up with three animations, the first one that runs on initial screen load (firstAnimation). Then the next two animations use callbacks to loop between themselves (slideAnimation -> rotateAnimation -> slideAnimation...)

How can I stop the animation whichever animation it's in using POINTERDOWN and resume it on PONTERUP..?

The way I have done it below works only during the firstAnimation, as soon as its in the loop it obviously no longer targets those two animations. So how would I target all three animations using a single .pause() .resume() command?

  var slideAnimation = function(){
      scene.beginDirectAnimation(box, [xSlide], 0, 2 * frameRate, false, 2, rotateAnimation);
  }

  var rotateAnimation = function(){
      scene.beginDirectAnimation(box, [yRot], 0, 2 * frameRate, false, 2, slideAnimation);
  }

  var firsAnimation = scene.beginDirectAnimation(box, [xSlide], 0, 2 * frameRate, false, 2, slideAnimation);

  scene.onPointerObservable.add((pointerInfo) => {
      switch (pointerInfo.type) {
          case BABYLON.PointerEventTypes.POINTERDOWN:
              light2.intensity =0.95;
              firsAnimation.pause();
              box.scaling = new BABYLON.Vector3(4, 1, -1)
              break;
          case BABYLON.PointerEventTypes.POINTERUP:
              light2.intensity =0.15;
              firsAnimation.restart();
              box.scaling = new BABYLON.Vector3(1, 1, 1)
              break;
      }
  });

Or does this need a different approach all together?


Solution

  • Babylon Group Animations could be useful for you - https://doc.babylonjs.com/how_to/group . It is a way to group animations and animatables, normalize then, and control them together.

    You can see an example here - https://www.babylonjs-playground.com/#CBGEQX#5

    If you want to see 2 animations running at the same time on one animatable (mesh), change line 79 from

    animationGroup.addTargetedAnimation(animation2, box2);
    

    to

    animationGroup.addTargetedAnimation(animation2, box1);
    

    And press the run button on the top.

    Then pressing the pay button will run both animations on the same mesh.