如何 tween/animate 迷雾 three.js

How to tween/animate fog three.js

所以我试图通过补间来改变雾的密度,这是可能的,因为它似乎没有改变这里是我的默认值:

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

这是我尝试使用库 GSAP 和 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;
                            
                        },
                    });

谁能指出我正确的方向?

此答案使用gsap

使用对象,例如。 myfog = { value: .5 } 并将其 value 属性 补间到你想要的。

然后在onUpdate中,将scene.fog设置为new THREE.FogExp2,当前myfog.value作为参数。

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>