Extending functionality of Entity

I’m trying to extend the functionality of Entity across the engine. I’m not using the editor and don’t want to fork the engine repo. I’d like to add some properties and methods to the pc Entity such as id.

I’ve tried setting prototype and overriding the constructor to no avail.

Here’s an example of what I’m trying to do:

import { Entity } from 'playcanvas';

export default class GameEntity extends Entity {
  id: string;

  constructor() {
    super('');

    this.id = generateId();
  }
}

Entity.prototype.constructor = GameEntity.prototype.constructor;

const e = new Entity();
console.log(e.id); // undefined

Patching the constructor is difficult due to how the Engine is bundled but you can extend Entity like you’ve done above much like Entity extends graph node:

However, this would mean you need to create GameEntities at runtime instead of Entities.

eg

function example(canvas: HTMLCanvasElement): void {
    class GameEntity extends pc.Entity {
        constructor(name : string, app? : pc.Application) {
            super(name, app || pc.Application.getApplication());
            console.log('hello');
        }
    }

    const app = new pc.Application(canvas, {});

    // create box entity
    const box = new GameEntity('cube');
    box.addComponent('render', {
        type: 'box'
    });
    app.root.addChild(box);

    // create camera entity
    const camera = new pc.Entity('camera');
    camera.addComponent('camera', {
        clearColor: new pc.Color(0.5, 0.6, 0.9)
    });
    app.root.addChild(camera);
    camera.setPosition(0, 0, 3);

    // create directional light entity
    const light = new pc.Entity('light');
    light.addComponent('light');
    app.root.addChild(light);
    light.setEulerAngles(45, 0, 0);

    // rotate the box according to the delta time since the last frame
    app.on('update', (dt: number) => box.rotate(10 * dt, 20 * dt, 30 * dt));

    app.start();
}

Tested in: https://playcanvas.github.io/#/misc/hello-world

1 Like