Finally Code in Niantic Studio Image target - Animation without restarting at image lost

This code works great!! Just I have situation. first time the sound works great but I need to open in incognite window to replay with sound again ( I have an splash screen to unlock audio)

If anyone needs Animation Code without restarting if image target is lost. (just pause it and play in time it left)

import * as ecs from ‘@8thwall/ecs’

ecs.registerComponent({
name: ‘PlayGLBClipOnImageFound’,
schema: {
model: ecs.eid, // Nodo del modelo GLB
clipName: ecs.string // Nombre del clip o “*” para reproducir todos
},

stateMachine: ({ world, eid, schemaAttribute }) => {
let savedTime = 0
let lastFrame = performance.now()

return ecs.defineState('default')
  .initial()

  // ▶️ Al detectar el target, reanudar desde tiempo guardado
  .listen(world.events.globalId, 'reality.imagefound', () => {
    const { model, clipName } = schemaAttribute.get(eid)

    ecs.GltfModel.set(world, model, {
      animationClip: clipName || '*',
      loop: false,
      paused: false,
      time: savedTime, // Reanuda desde donde se quedó
      timeScale: 1,
      crossFadeDuration: 0
    })

    lastFrame = performance.now()
    console.log(`▶️ Animación reanudada desde ${savedTime.toFixed(2)}s`)
  })

  // ⏸️ Al perder el target, guardar el tiempo actual
  .listen(world.events.globalId, 'reality.imagelost', () => {
    const { model } = schemaAttribute.get(eid)
    const modelData = ecs.GltfModel.get(world, model)

    if (modelData) {
      // Calcular tiempo transcurrido desde el último frame
      const now = performance.now()
      const delta = (now - lastFrame) / 1000 // a segundos
      savedTime = (modelData.time || 0) + delta

      // Pausar la animación
      ecs.GltfModel.mutate(world, model, (c) => {
        c.paused = true
      })

      console.log(`⏸️ Animación pausada en ${savedTime.toFixed(2)}s`)
    } else {
      console.warn('⚠️ No se pudo obtener el modelo para pausar.')
    }
  })

}
})