I’d like to connect to an API and when the AR experience launches I make a call to the API and load it into the scene
import * as ecs from ‘@8thwall/ecs’
const {XR8} = window as any
ecs.registerComponent({
name: ‘random-model-api’,
schema: {},
schemaDefaults: {},
data: {
modelUrl: ecs.string,
name: ecs.string,
},
add: (world, component) => {
fetch(‘https://immersive-commerce.vercel.app/api/models’)
.then(res => res.json())
.then((data) => {
// Select a random model from the fetched data
const randomIndex = Math.floor(Math.random() * data.length)
const selectedModel = data[randomIndex]
// Set model data
component.data.modelUrl = selectedModel.glbUrl
component.data.name = selectedModel.name
// Create an entity for the selected model
const entity = world.createEntity()
// Add components to the entity
entity.addComponent(ecs.GltfModel, {
url: component.data.modelUrl,
scale: {x: 0.5, y: 0.5, z: 0.5},
})
entity.addComponent(ecs.Position, {
x: 0,
y: 0,
z: -3,
})
entity.addComponent(ecs.Collider, {
type: 'box',
})
// Check if the GLTF model was loaded
world.on(ecs.events.GLTF_MODEL_LOADED, (event) => {
if (event.model === entity.getComponent(ecs.GltfModel).model) {
console.log(`Model loaded: ${component.data.name}`)
}
})
// Update UI with the model name
ecs.Ui.mutate(world, component.eid, (cursor) => {
const text = `Loaded Model: ${component.data.name}`
cursor.text = text
cursor.width = text.length * cursor.fontSize * 0.2
return false
})
})
.catch((e) => {
console.error('Error fetching 3D models:', e)
})
// Center the view on click or touch
window.addEventListener('click', XR8.XrController.recenter)
window.addEventListener('touchstart', XR8.XrController.recenter)
},
tick: (world, component) => {
// Logic to be executed on each tick if necessary
},
remove: (world, component) => {
// Cleanup logic here if necessary
},
})
This is my code, but it’s not working I get the error entity.addComponent is not a function