[SOLVED] Examples of ES6 based PlayCanvas scripts

Where I can find some examples of es6 classes in Playcanvas as the support is added as v 1.26.0?

I only see this

class PlayerController extends pc.ScriptType {

    initialize() {
        // called once on initialize
    }

    update(dt) {
        // called each tick
    }
}

// register the class as a script
pc.registerScript(PlayerController);
1 Like

Hi @grzesiekmq and welcome,

There isn’t any ES6 specific example on how to do things, but that template is actually all you need to start using ES6 scripts.

The initialize and update code of ES5 scripts should be placed accordingly in the ES6 class methods.

If you are talking about using ES6 specific features like async/await or string template literals you can still use them, just note the Playcanvas code editor will complain with some of them.

Here is a simple example of a ES5 styled script with some ES6 features in Typescript:

const PositionEntity = pc.createScript("positionEntity");

// initialize code called once per entity
PositionEntity.prototype.initialize = async function() {
  const entity: pc.Entity = this.entity;

  for (let index = 0; index < 10; index++) {
    entity.translate(1, 0, 0);

    await sleep(150);
  }
};

// --- Utilities
function sleep(ms: number) {
  return new Promise(resolve => setTimeout(resolve, ms));
}
2 Likes