Only the last one plays the animation, I want them all to play the animations

My code is in the 8th platform, the code is below


  let mixer = null

  function randomNumberInterval(a, b) {
    return Math.floor(Math.random() * (b - a + 1)) + a
  }

  const animateIn = (model, pointX, pointZ, yDegrees) => {
    model.scene.rotation.set(0.0, yDegrees, 0.0)
    model.scene.position.set(pointX, 0.0, pointZ)
    model.scene.scale.set(0.015, 0.015, 0.015)
    model.scene.traverse((child) => {
      if (child instanceof THREE.Mesh) {
        child.castShadow = true
      }
    })
    mixer = new THREE.AnimationMixer(model.scene)
    const action = mixer.clipAction(model.animations[randomNumberInterval(0, 2)])
    action.play()
    XR8.Threejs.xrScene().scene.add(model.scene)
  }

  const placeObject = (pointX, pointZ) => {
    loader.load(
      modelFile,
      (gltf) => {
        animateIn(gltf, pointX, pointZ, Math.random() * 360)
      }
    )
  }

     const clock = new THREE.Clock()
      let previousTime = 0

      const tick = () => {
        const elapsedTime = clock.getElapsedTime()
        const deltaTime = elapsedTime - previousTime
        previousTime = elapsedTime

        if (mixer != null) {
            mixer?.update(deltaTime)
        }

        renderer.render(scene, camera)

        window.requestAnimationFrame(tick)
      }

      tick()

Your mixer is a global variable that’s being overwritten every time you place a new object, you can rather make an array of mixers, something like this…

  let mixers = [] 

  function randomNumberInterval(a, b) {
    return Math.floor(Math.random() * (b - a + 1)) + a
  }

  const animateIn = (model, pointX, pointZ, yDegrees) => {
    model.scene.rotation.set(0.0, yDegrees, 0.0)
    model.scene.position.set(pointX, 0.0, pointZ)
    model.scene.scale.set(0.015, 0.015, 0.015)
    model.scene.traverse((child) => {
      if (child instanceof THREE.Mesh) {
        child.castShadow = true
      }
    })
    const mixer = new THREE.AnimationMixer(model.scene)
    mixers.push(mixer)
    const action = mixer.clipAction(model.animations[randomNumberInterval(0, 2)])
    action.play()
    XR8.Threejs.xrScene().scene.add(model.scene)
  }
const placeObject = (pointX, pointZ) => {
    loader.load(
      modelFile,
      (gltf) => {
        animateIn(gltf, pointX, pointZ, Math.random() * 360)
      }
)}

const clock = new THREE.Clock()
let previousTime = 0

const tick = () => {
        const elapsedTime = clock.getElapsedTime()
        const deltaTime = elapsedTime - previousTime
        previousTime = elapsedTime

        if (mixers.length) {
            mixers.forEach(m=>{
               m.update(deltaTime)
            } 
        }

   renderer.render(scene, camera)

   window.requestAnimationFrame(tick)
}

tick()


thank you very much, it worked

1 Like