Creazione di Oggetti a Runtime

Molto spesso, giochi o applicazioni aggiungono nuovi oggetti a runtime, magari in risposta all’utente o per generare un effetto visivo.

In Wonderland Engine, puoi creare oggetti da un componente JavaScript personalizzato utilizzando Scene.addObject o Scene.addObjects.

Aggiungere un Singolo Oggetto 

Aggiungere un singolo oggetto viene eseguito tramite Scene.addObject:

import {Component, Property} from '@wonderlandengine/api';

export class Spawner extends Component {
  static TypeName = 'spawner';
  static Properties = {
    mesh: Property.mesh(),
    material: Property.material(),
  };

  start() {
    /* Genera un nuovo oggetto con this.object come genitore */
    const o = this.engine.scene.addObject(this.object);

    /* Aggiunge un componente mesh */
    o.addComponent('mesh', {
      mesh: this.mesh,
      material: this.material,
    });
  }
}

Aggiungere Molti Oggetti 

Per aggiungere più oggetti, Scene.addObjects offre migliori prestazioni:

import {Component, Property} from '@wonderlandengine/api';

export class BatchSpawner extends Component {
  static TypeName = 'batch-spawner';
  static Properties = {
    mesh: Property.mesh(),
    material: Property.material(),
    count: Property.int(10),
  };

  start() {
    /* Genera 'count' nuovi oggetti con this.object come genitore e informa Wonderland Engine che avremo bisogno di 'count' componenti (uno per oggetto) */
    const objs = this.engine.scene.addObjects(10, this.object, this.count);

    /* Aggiunge i mesh */
    for(let o of objs) {
      o.addComponent('mesh', {
        mesh: this.mesh,
        material: this.material,
      });
      /* Posiziona l'oggetto in una posizione casuale in un volume di cubo 10x10x10 */
      o.translate([Math.random()*10, Math.random()*10, Math.random()*10]);
    }
  }
}