class PlayerInstance extends globalThis.InstanceType.Player
{
constructor()
{
super();
// Start with 5 bullets
this.ammo = 5;
}
shoot()
{
// Decrement ammo count
this.ammo--;
// create a bullet instance, etc.
}
}
Note that here ammo
is not an instance variable or anything else associated with Construct's event system: it's just a normal JavaScript object property.
Since IInstance has a runtime
property, within your class you can always use this.runtime
to refer to the runtime script interface.
use your custom features
Now whenever you retrieve instances of the player from the existing APIs, you'll get PlayerInstance
classes instead of the default based on ISpriteInstance
. Then you can read your custom properties and call custom methods.
// Assume called in "beforelayoutstart" event
function OnBeforeLayoutStart(runtime)
{
// Get player instance from Construct
const playerInstance = runtime.objects.Player.getFirstInstance();
// Example uses of custom class
console.log("Ammo = " + playerInstance.ammo);
playerInstance.shoot();
}
Conclusion
Subclassing is straightforward to set up, and lets you use custom classes for different objects in your project. This can make your code a lot clearer, and helps you to use the full power of JavaScript classes with instances in Construct's runtime.