ランタイムでのオブジェクト生成

ゲームやアプリケーションでは、ユーザーの操作に反応したり、ビジュアルエフェクトを生成するためにランタイムで新しいオブジェクトを追加することが非常に頻繁にあります。

Wonderland Engineでは、カスタムJavaScriptコンポーネントを使用して、Scene.addObject または Scene.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);

    /* メッシュをアタッチ */
    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() {
    /* this.objectを親として'count'の数だけ新しいオブジェクトを生成し、
     * それぞれにコンポーネントを必要とすることをWonderland Engineに知らせます */
    const objs = this.engine.scene.addObjects(10, this.object, this.count);

    /* メッシュをアタッチ */
    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]);
    }
  }
}