如何使用 Tween.js 缩放 Three.js 中的 3d 对象

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

有谁知道如何使用 tween.js 库来平滑地缩放 three.js 中的对象?例如,如果我有一个 3d 立方体,我怎样才能让它缩小,然后用一个流畅的动画让它 return 恢复到正常大小。如果您能提供任何帮助或示例,我将不胜感激。谢谢

使用以下基本示例作为代码模板。

var camera, scene, renderer;

init();
animate();

function init() {

    camera = new THREE.PerspectiveCamera( 70, window.innerWidth / window.innerHeight, 0.01, 10 );
    camera.position.z = 1;

    scene = new THREE.Scene();

    var geometry = new THREE.PlaneGeometry( 0.2, 0.2 );
    var material = new THREE.MeshBasicMaterial();

    var mesh = new THREE.Mesh( geometry, material );
    scene.add( mesh );

    renderer = new THREE.WebGLRenderer( { antialias: true } );
    renderer.setSize( window.innerWidth, window.innerHeight );
    document.body.appendChild( renderer.domElement );
    
    var targetPosition = new THREE.Vector3( 0, 0, 0 );
    
    // create animation
    
    new TWEEN.Tween( mesh.scale )
     .to( targetPosition )
      .repeat( Infinity )
      .yoyo( true )
      .easing( TWEEN.Easing.Cubic.InOut )
      .start();

}

function animate() {

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

}
body {
  margin: 0;
}
canvas {
  display: block;
}
<script src="https://cdn.jsdelivr.net/npm/three@0.116/build/three.js"></script>
<script src="https://cdn.jsdelivr.net/npm/@tweenjs/tween.js@18.5.0/dist/tween.umd.js"></script>

还有更有趣的事:

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>