Search code examples
javascriptthree.jstween

Cannot see tween opacity changing effect in threeJS


<script type="importmap">
      {
        "imports": {
         "three": "https://unpkg.com/[email protected]/build/three.module.js",
         "three/addons/": "https://unpkg.com/[email protected]/examples/jsm/" 
        }
      }
</script>
<script type="module" style="position: absolute; z-index: 100;">
    import TWEEN from 'https://cdn.jsdelivr.net/npm/@tweenjs/[email protected]/dist/tween.esm.js';
    import * as THREE from 'three';

    const scene = new THREE.Scene();
    const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 10;
    const renderer = new THREE.WebGLRenderer();
    renderer.setSize(window.innerWidth, window.innerHeight);
    document.body.appendChild(renderer.domElement);
     

    var cube = new THREE.Mesh(new THREE.BoxGeometry(2, 2, 2), new THREE.MeshBasicMaterial({
        color: "red",
        transparent: true
    }));
    scene.add(cube);


    window.onload=function(){
        var el_my_button = document.getElementById("my_button");

        el_my_button.addEventListener("click", function(event) {
            var tweenoff = new TWEEN.Tween(cube.material).to({
                opacity: 0
            }, 2000).onComplete(function(){
                cube.visible = false;
            });

            console.log( tweenoff );
            tweenoff.start();
        });
    }


    function animate() {
      requestAnimationFrame(animate);
      renderer.render(scene, camera);
    }
    animate();
</script>
<div id="my_button" style="background: #ccc; width:100; height: 50px; margin-top:50px; position: absolute; z-index: 101;">    
    my_button
</div>

Opacity of cube did not changing, there is no any error, but there is no any effect as well from TWEEN, after click on "my_button". What is issue here? I guess I'm wrongly importing tween.js library, or that is incompatible with three.js version? but not sure. Any help appreciated.


Solution

  • You have to call TWEEN.update(); inside your animation loop.

    function animate() {
        requestAnimationFrame(animate);
        TWEEN.update();
        renderer.render(scene, camera);
    }
    

    Full demo: https://jsfiddle.net/ubh2mjq1/2/