diff --git a/autoplayer.js b/autoplayer.js new file mode 100644 index 00000000..d147947f --- /dev/null +++ b/autoplayer.js @@ -0,0 +1,47 @@ +// autoplayer.js + +export class AutoPlayer { + constructor(diorama, speed = 1.0) { + this.frame = diorama.frame; + this.speed = speed; + + this.lastFrameTime = performance.now(); + this.playheadTime = 0; + this.isRunning = true; + + this._loop = this.loop.bind(this); + requestAnimationFrame(this._loop); + } + + getMaxTime() { + const evs = this.frame.world.events; + return evs.length > 0 ? evs[evs.length - 1].time : 0; + } + + loop(time) { + if (!this.isRunning) return; + + const dt = (time - this.lastFrameTime) / 1000; + this.lastFrameTime = time; + const maxTime = this.getMaxTime(); + + // Only animate if there are actually forward events in the timeline + if (maxTime > 0) { + this.playheadTime += dt * 20 * this.speed; + + // Loop wrap-around + if (this.playheadTime >= maxTime) { + this.playheadTime = this.playheadTime % maxTime; + } + + this.frame.seek(this.playheadTime); + } + + requestAnimationFrame(this._loop); + } + + // Call this if you ever need to destroy the diorama and stop the memory leak + stop() { + this.isRunning = false; + } +} \ No newline at end of file