在运行时生成对象

在游戏或应用程序中,通常会在运行时添加新对象,也许是对用户的反应,或者是生成视觉效果。

在Wonderland Engine中,可以通过自定义JavaScript组件来创建对象,使用Scene.addObjectScene.addObjects

添加单个对象 

添加单个对象通过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() {
    /* 创建一个新的对象,并将其父对象设置为this.object */
    const o = this.engine.scene.addObject(this.object);

    /* 附加一个mesh组件 */
    o.addComponent('mesh', {
      mesh: this.mesh,
      material: this.material,
    });
  }
}

添加多个对象 

要添加多个对象,Scene.addObjects可以提供更好的性能:

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() {
    /* 创建'count'个新的对象,将其父对象设置为this.object,并通知Wonderland Engine,我们需要'count'个组件(每个对象一个) */
    const objs = this.engine.scene.addObjects(10, this.object, this.count);

    /* 附加mesh组件 */
    for(let o of objs) {
      o.addComponent('mesh', {
        mesh: this.mesh,
        material: this.material,
      });
      /* 将对象随机放置在10x10x10的立方体体积中 */
      o.translate([Math.random()*10, Math.random()*10, Math.random()*10]);
    }
  }
}