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:

 1import {Component, Property} from '@wonderlandengine/api';
 2
 3export class Spawner extends Component {
 4  static TypeName = 'spawner';
 5  static Properties = {
 6    mesh: Property.mesh(),
 7    material: Property.material(),
 8  };
 9
10  start() {
11    /* Spawn a new object with this.object as parent */
12    const o = this.engine.scene.addObject(this.object);
13
14    /* Attach a mesh */
15    o.addComponent('mesh', {
16      mesh: this.mesh,
17      material: this.material,
18    });
19  }
20}

Add Many Objects 

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

 1import {Component, Property} from '@wonderlandengine/api';
 2
 3export class BatchSpawner extends Component {
 4  static TypeName = 'batch-spawner';
 5  static Properties = {
 6    mesh: Property.mesh(),
 7    material: Property.material(),
 8    count: Property.int(10),
 9  };
10
11  start() {
12    /* Spawn 'count' new objects with this.object as parent and
13     * let Wonderland Engine know, we will need 'count' components (one per object) */
14    const objs = this.engine.scene.addObjects(10, this.object, this.count);
15
16    /* Attach meshes */
17    for(let o of objs) {
18      o.addComponent('mesh', {
19        mesh: this.mesh,
20        material: this.material,
21      });
22      /* Place object at random location in 10x10x10 cube volume */
23      o.translate([Math.random()*10, Math.random()*10, Math.random()*10]);
24    }
25  }
26}