Spawning Objects at Runtime

Very frequently, games or apps add new objects at runtime, maybe in reaction to the user or for spawning a visual effect.

In Wonderland Engine, you can create objects from a custom JavaScript component either using Scene.addObject or Scene.addObjects.

Add a Single Object 

Adding a single object is done via 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() {
    /* Spawn a new object with this.object as parent */
    const o = this.engine.scene.addObject(this.object);

    /* Attach a mesh */
    o.addComponent('mesh', {
      mesh: this.mesh,
      material: this.material,
    });
  }
}

Add Many Objects 

For adding multiple objects, Scene.addObjects yields better performance:

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() {
    /* Spawn 'count' new objects with this.object as parent and
     * let Wonderland Engine know, we will need 'count' components (one per object) */
    const objs = this.engine.scene.addObjects(10, this.object, this.count);

    /* Attach meshes */
    for(let o of objs) {
      o.addComponent('mesh', {
        mesh: this.mesh,
        material: this.material,
      });
      /* Place object at random location in 10x10x10 cube volume */
      o.translate([Math.random()*10, Math.random()*10, Math.random()*10]);
    }
  }
}