“I am working on creating a 5-image target with 5 different animations and corresponding sounds. While I successfully managed to play the GLB animations when a tracker is detected, the sound isn’t playing as expected. I’m unable to figure out what’s wrong in the code. I’m using the Cloud Editor for this project. . This is urgent.”
app.js-
window.onload = function () {
const targets = [
{targetId: ‘target1’, entityId: ‘entity1’},
{targetId: ‘target2’, entityId: ‘entity2’},
{targetId: ‘target3’, entityId: ‘entity3’},
{targetId: ‘target4’, entityId: ‘entity4’},
{targetId: ‘target5’, entityId: ‘entity5’},
]
let currentIndex = 0
function activateTarget(index) {
// Deactivate all targets
targets.forEach(({targetId}) => {
const target = document.getElementById(targetId)
if (target) target.setAttribute(‘visible’, ‘false’)
})
// Activate the current target
const {targetId, entityId} = targets[index]
const target = document.getElementById(targetId)
const entity = document.getElementById(entityId)
if (target) {
target.setAttribute('visible', 'true')
const onImageFound = () => {
// Play sound
const soundComponent = entity.components.sound
if (soundComponent) {
soundComponent.playSound()
} else {
console.error('error1')
}
// Cleanup listener after playing
target.removeEventListener('xrimagefound', onImageFound)
// Move to the next target after a delay
setTimeout(() => {
currentIndex = (currentIndex + 1) % targets.length
activateTarget(currentIndex)
}, 5000)
}
target.addEventListener('xrimagefound', onImageFound)
} else {
console.error('error2')
}
}
// Add a click listener to unlock audio
document.body.addEventListener(‘click’, () => {
const entities = targets.map(({entityId}) => document.getElementById(entityId))
entities.forEach((entity) => {
if (entity && entity.components.sound) {
entity.components.sound.playSound()
entity.components.sound.stopSound()
}
})
})
// Start with the first target
activateTarget(currentIndex)
}