How to handle initialize, update and function in es6?

Hello,

I want to know how i can use es6 in project like…
basic init, update and function structure which can be used to target entity as well…

Example project or snippet will be helpful.

In one of my games, I used only es6 scripts. Didn’t have to change any function structure, just a few keywords, such as changing var to let. Check this out for the full list of changes.

All you have to do is add /* jshint esversion: 6 */ at the top of your code.

Check my script from aforementioned game here - https://playcanvas.com/editor/code/653630?tabs=25835096.

It depends on the functions you are writing but mainly you can do is:

  • Replace “var” variables with “let” variable that are way more better then var
  • Use Arrow functions to improve readability of code also if you are using arrow function in settimeout() then you dont have to worry about the “this” issue. Here is a syntax for that:
setTimeout(() => {
        this.anyBool = true;
    }, 1000);
  • Also the other exciting feature is introduction of classes by which you can intiliaze the object through constructor function of any class. For instance
SampleClass.prototype.initialize = function() {
    

    class Person {
        constructor(name,age,gender){
            this.name = name;
            this.age = age;
            this.gender = gender;
        }
    } 

let person = new Person("Jack",30,M);
};
  • Also some new functions are introduced and you can check them out on the js6 info.

A PlayCanvas script based on ES6 class syntax looks like this:

/* jshint esversion: 6 */

// define a ES6 script class
class PlayerController extends pc.ScriptType {

    initialize() {
        // called once on initialize
    }

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

// register the class as a script
pc.registerScript(PlayerController, 'playerController');

// declare script attributes (Must be after pc.registerScript())
PlayerController.attributes.add('attribute1', {type: 'number'});
8 Likes