在Three.js中,当某个条件成立后,如何继续播放动画

前端开发 2026-07-10

我想要创建一组不断循环、向上移动的对象。

这些对象是网格,或者墙。我打算在墙体刚好走出摄像头视野时就删除它,然后再创建一个新墙。

现在我只是把现有的网格重新放到屏幕底部,但动画在那之后就停止了。这是为什么?有人能解释正确的做法吗?我也尝试过一个创建新网格的函数,但它根本不起作用。

这是我的代码。在if语句之后,它就不再移动了。

import * as THREE from 'three';

const renderer = new THREE.WebGLRenderer();
renderer.setSize( window.innerWidth, window.innerHeight );
document.body.appendChild( renderer.domElement );

const scene = new THREE.Scene();
const camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 );

camera.position.set(0, 0, 10) 

var Wall = new THREE.GridHelper( 10, 5 );
Wall.rotation.x = 180;
scene.add( Wall );

function animate( time ) {
    Wall.position.y = -15 + time / 200;

    if (Wall.position.y > 5) {
        Wall.position.y = 0
    } 
    //console.log(Wall.position.y)
    renderer.render( scene, camera );


}
renderer.setAnimationLoop( animate );

解决方案

在 ànimate中的time` 变量会持续增加,最终超过你的视口。

其中最常用的解决方案之一是使用取模运算符,使它在每经过n 次更新时重新回绕回去:

  function animate(time) {
      Wall.position.y = -15 + ((time / 200) % 20);
      renderer.render(scene, camera);
  }
body { margin: 0; overflow: hidden; }
<script type="module">
  import * as THREE from "https://cdn.jsdelivr.net/npm/[email protected]/build/three.module.js";

  const renderer = new THREE.WebGLRenderer();
  renderer.setSize(window.innerWidth, window.innerHeight);
  document.body.appendChild(renderer.domElement);

  const scene = new THREE.Scene();
  const camera = new THREE.PerspectiveCamera(75, window.innerWidth / window.innerHeight);
  camera.position.set(0, 0, 10);

  const Wall = new THREE.GridHelper(10, 5);
  Wall.rotation.x = Math.PI;
  scene.add(Wall);

  function animate(time) {
    Wall.position.y = -15 + ((time / 200) % 20);
    renderer.render(scene, camera);
  }

  renderer.setAnimationLoop(animate);

  window.addEventListener("resize", () => {
    camera.aspect = window.innerWidth / window.innerHeight;
    camera.updateProjectionMatrix();
    renderer.setSize(window.innerWidth, window.innerHeight);
  });
</script>
站内所有文章版权归属LeftHeroAI导航站,无授权禁止任何主体转载、抄袭、复制内容,亦不得私自架设镜像站点。一经侵权,本站将通过法律途径追责。

相关文章