animationthree.jstween.jstweenjs

How to use Tween.js to scale a 3d object in Three.js


does anyone know how I could use tween.js library to smoothly scale objects in three.js? Like for instance if I had a 3d cube how could I make it shrink and then have it return back to its normal size all with one smooth animation. I would appreciate any help or examples you could provide. Thanks


Solution

  • And something more funny:

    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(60, innerWidth / innerHeight, 1, 100);
    camera.position.set(1, 5, 3);
    camera.lookAt(scene.position);
    var renderer = new THREE.WebGLRenderer();
    renderer.setSize(innerWidth, innerHeight);
    document.body.appendChild(renderer.domElement);
    
    var box = new THREE.Mesh(new THREE.BoxBufferGeometry(2, 2, 2), new THREE.MeshBasicMaterial({
      wireframe: true
    }));
    scene.add(box);
    box.userData.isTweening = false;
    
    btn.addEventListener("click", event => {
      if (box.userData.isTweening) return;
      var tweenInflate = new TWEEN.Tween(box.scale).to({
        x: 2,
        y: 2,
        z: 2
      }, 1500).easing(TWEEN.Easing.Elastic.Out).onStart(() => {
        box.userData.isTweening = true;
      });
      var tweenDeflate = new TWEEN.Tween(box.scale).to({
        x: 1,
        y: 1,
        z: 1
      }, 1000).onComplete(() => {
        box.userData.isTweening = false;
      });
      tweenInflate.chain(tweenDeflate);
      tweenInflate.start();
    }, false);
    
    renderer.setAnimationLoop(() => {
      TWEEN.update();
      renderer.render(scene, camera);
    });
    body {
      overflow: hidden;
      margin: 0;
    }
    
    button {
      position: absolute;
      margin: 5px;
    }
    <script src="https://threejs.org/build/three.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/tween.js/16.7.0/Tween.js"></script>
    <button id="btn">tweenme</button>