Search code examples
javascriptthree.jsgsaptween.js

How to tween/animate fog three.js


So i am trying to change the fog density by tweening it is this possible because it doesn't seem to change here's my defaults:

var camera, densityFog, colorFog2;
                    colorFog2 = 0xfee2ed;
                    densityFog = 0.25;
                    scene.fog = new THREE.FogExp2(colorFog2, densityFog);

and here is what I've tried using the libs GSAP and tweenjs:

tween = new TWEEN.Tween(scene.fog)
                .to({densityFog: 0.02}, 1000 )
                .easing(TWEEN.Easing.Exponential.InOut)
                .onComplete(function() { }).start();
                    
                gsap.to(scene.fog, {
                        duration: 2,
                        densityFog: 0.02,
                        onUpdate: function () {
                            controls.update();
                            isZoomed = 0;
                            controls.enabled = false;
                            
                        },
                    });

can anyone point me in the right direction?


Solution

  • This answer uses gsap

    Use an object eg. myfog = { value: .5 } and tween its value property to what you desire.

    Then in onUpdate, set scene.fog to a new THREE.FogExp2 with the current myfog.value as a parameter.

    var scene = new THREE.Scene();
    var camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight, 0.1, 1000);
    camera.position.z = 5;
    camera.position.y = 2;
    
    // Init the object and fog here
    var myfog = { value: .5 }
    scene.fog = new THREE.FogExp2(0x00ff00, myfog.value);
    
    var geometry = new THREE.BoxGeometry(1, 1, 5);
    var mat = new THREE.MeshBasicMaterial({
      color: 0xff0000
    });
    var mesh = new THREE.Mesh(geometry, mat);
    
    scene.add(mesh);
    
    var renderer = new THREE.WebGLRenderer({
      antialias: true
    });
    renderer.setSize(window.innerWidth, window.innerHeight);
    renderer.setClearColor(0x00ff00);
    document.body.appendChild(renderer.domElement);
    
    function render() {
      renderer.render(scene, camera);
    }
    
    function animate() {
      requestAnimationFrame(animate);
      render();
    }
    
    animate();
    
    // This animates the fog
    gsap.to(myfog, {
      duration: 2,
      value: 0.002, // The end value
      onUpdate: function() {
        // New fog with current myfog value
        scene.fog = new THREE.FogExp2(0x00ff00, myfog.value);
      },
      // These just infinitely repeat the animation
      yoyo: true,
      repeat: -1,
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/gsap/3.6.1/gsap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/three.js/r127/three.min.js"></script>