Skip to content

Instantly share code, notes, and snippets.

@samme
Created March 13, 2024 17:09
Show Gist options
  • Save samme/8274796a7f2c6bc5e810adec6acd022f to your computer and use it in GitHub Desktop.
Save samme/8274796a7f2c6bc5e810adec6acd022f to your computer and use it in GitHub Desktop.
Global clock plugin for Phaser 3
/* global Phaser */
// GlobalClock
// Modified from Phaser.Time.Clock by Richard Davey © 2013-2023 Photon Storm Ltd. <https://opensource.org/licenses/MIT>
class GlobalClock {
constructor(pluginManager) {
this.pluginManager = pluginManager;
this.game = pluginManager.game;
this.now = 0;
this.startTime = 0;
this.timeScale = 1;
this.paused = false;
this._active = [];
this._pendingInsertion = [];
this._pendingRemoval = [];
}
init() {}
start() {
this.startTime = this.game.loop.time;
this.game.events
.on('prestep', this.preUpdate, this)
.on('step', this.update, this);
}
stop() {
for (i = 0; i < this._pendingInsertion.length; i++) {
this._pendingInsertion[i].destroy();
}
for (i = 0; i < this._active.length; i++) {
this._active[i].destroy();
}
for (i = 0; i < this._pendingRemoval.length; i++) {
this._pendingRemoval[i].destroy();
}
this.game.events
.off('prestep', this.preUpdate, this)
.off('step', this.update, this);
}
destroy() {
this.stop();
this.pluginManager = null;
this.game = null;
this._active.length = 0;
this._pendingRemoval.length = 0;
this._pendingInsertion.length = 0;
}
}
{
const {
addEvent,
clearPendingEvents,
delayedCall,
preUpdate,
removeAllEvents,
removeEvent,
update,
} = Phaser.Time.Clock.prototype;
Object.assign(GlobalClock.prototype, {
addEvent,
clearPendingEvents,
delayedCall,
preUpdate,
removeAllEvents,
removeEvent,
update,
});
}
// Example:
new Phaser.Game({
plugins: {
global: [
{ key: 'GlobalClock', plugin: GlobalClock, mapping: 'globalTime' },
],
},
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment