To be able to call your game scripts from an outer context (like the buttons, they are in the HTML document context, not the PlayCanvas app context), you have to declare static functions.
So let’s see, this is how a standard playcanvas script looks like:
var Rotate = pc.createScript('rotate');
Rotate.attributes.add('speed', { type: 'number', default: 10 });
// initialize code called once per entity
Rotate.prototype.initialize = function() {
this.local = false; // choose local rotation or world rotation
};
// update code called every frame
Rotate.prototype.update = function(dt) {
if (this.local) {
this.entity.rotateLocal(0, this.speed * dt, 0);
} else {
this.entity.rotate(0, this.speed * dt, 0);
}
};
Rotate.prototype.RotateSpecified = function(degrees){
this.entity.rotate(0, degrees, 0);
};
// swap method called for script hot-reloading
// inherit your script state here
Rotate.prototype.swap = function(old) {
this.local = old.local;
};
Now, you can’t call anything on that script from another script directly, because it has its own context.
To call it, you would need to create a static reference to this script’s context. How?
As easy as this:
// initialize code called once per entity
Rotate.prototype.initialize = function() {
this.local = false; // choose local rotation or world rotation
Rotate.instance = this; // expose the Rotate script with a static instance variable.
};
Now, from a HTML perspective, you could call “Rotate.instance.RotateSpecified(90);” on the DOM “onclick” event, and it would work successfully, because it is a direct reference to “Rotate.prototype” context.
Like this:
<button onclick="Rotate.instance.RotateSpecified(90)">Rotate!</button>
I hope this example has helped you out. Coding can be confusing and frustrating when you’re new to it. But just give it time and learn about how does it all works.
Now, I don’t personally create static references inside the scripts themselves, I just create a “Manager” script where I set all of the references so it’s more comprehensible and quicker to access. But the example above is the simplest way I could think of.