如何在Three.js中实现立方体上下往复循环移动的效果
Three.js 立方体上下往复移动实现方案
原代码仅单次执行y轴增量逻辑,且存在拼写错误HREE.BoxGeometry需修正为THREE.BoxGeometry,要实现持续往复移动,需将更新逻辑放入帧渲染循环中,可选用以下两种方案实现:
方案1:边界判断切换方向(可控性高)
通过手动定义移动边界、方向变量,触达边界时反转方向实现匀速往复:
// 模型初始化(修正原代码笔误) const BoxGeo = new THREE.BoxGeometry(10,10,10) const BoxMat = new THREE.MeshPhongMaterial({ color: 0xf3e54f }) const cab = new THREE.Mesh(BoxGeo, BoxMat) scene.add(cab) // 新增往复控制参数 const speed = 1 // 移动速度 const minY = 0 // 最低停留位置 const maxY = 20 // 最高停留位置 let direction = 1 // 移动方向:1为向上,-1为向下 // Three.js 渲染循环(所有动态更新逻辑需放在此循环内执行) function animate() { requestAnimationFrame(animate) // 位置更新+边界判断 cab.position.y += speed * direction if (cab.position.y >= maxY || cab.position.y <= minY) { direction *= -1 // 触达边界时反转方向 } renderer.render(scene, camera) } animate()
方案2:正弦函数实现平滑往复(代码更简洁)
利用Math.sin()值域固定为[-1,1]的特性,结合时间变量自动生成缓入缓出的往复位置,无需手动判断边界:
// 模型初始化同上 const BoxGeo = new THREE.BoxGeometry(10,10,10) const BoxMat = new THREE.MeshPhongMaterial({ color: 0xf3e54f }) const cab = new THREE.Mesh(BoxGeo, BoxMat) scene.add(cab) // 新增往复控制参数 const centerY = 10 // 上下移动的中心点y坐标 const moveRange = 10 // 上下移动的幅度(中心点上下各移动10单位) const speed = 0.02 // 移动速度,数值越大往复越快 function animate() { requestAnimationFrame(animate) // 直接通过正弦函数计算当前帧y轴位置 cab.position.y = centerY + Math.sin(Date.now() * speed) * moveRange renderer.render(scene, camera) } animate()
内容的提问来源于stack exchange,提问作者It's Joker
相关产品推荐
相关产品推荐

