Jesse
Jesse

Reputation: 41

How can I make my entity appear only once in my scence on A-Frame?

In this specific every time I tap on the screen the entity would appear multiple times (many #treeModel 's). My intention is just to make one model to pop out, no matter how many times I tap on the screen.

init() {
    this.raycaster = new THREE.Raycaster()
    this.camera = document.getElementById('camera')
    this.threeCamera = this.camera.getObject3D('camera')
    this.ground = document.getElementById('ground')

    // 2D coordinates of the raycast origin, in normalized device coordinates (NDC)---X and Y
    // components should be between -1 and 1.  Here we want the cursor in the center of the screen.
    this.rayOrigin = new THREE.Vector2(0, 0)

    this.cursorLocation = new THREE.Vector3(0, 0, 0)

    this.el.sceneEl.addEventListener('click', (event) => {
      // Create new entity for the new object
      const newElement = document.createElement('a-entity')

      // Spawn model at location of the cursor
      newElement.setAttribute('position', this.el.object3D.position)

      const randomYRotation = Math.random() * 360
      newElement.setAttribute('rotation', `0 ${randomYRotation} 0`)

      newElement.setAttribute('visible', 'false')
      newElement.setAttribute('scale', '0.0001 0.0001 0.0001')

      newElement.setAttribute('gltf-model', '#treeModel')
      newElement.setAttribute('shadow', {receive: false})

      this.el.sceneEl.appendChild(newElement)

      newElement.addEventListener('model-loaded', () => {
        // Once the model is loaded, we are ready to show it popping in using an animation
        newElement.setAttribute('visible', 'true')
        newElement.setAttribute('animation', {
          property: 'scale',
          to: '10 10 10',
          easing: 'easeOutElastic',
          dur: 800,
        })
      })
    })
  }

Upvotes: 0

Views: 108

Answers (1)

Piotr Adam Milewski
Piotr Adam Milewski

Reputation: 14645

Create the model once, and move it on click, ie:

  • create the element before the click, but keep it hidden (via the visible attribute)
  • on click, change its position and make it visible.

Upvotes: 0

Related Questions