From 97fb30d7418231d4a76a6b0d01a321a2ac957e92 Mon Sep 17 00:00:00 2001 From: Uwe Oestermeier Date: Thu, 20 Jul 2023 14:38:23 +0200 Subject: [PATCH] Moved throws to a single loop. --- lib/scatter.js | 79 +++++++++++++++++--------------------------------- 1 file changed, 27 insertions(+), 52 deletions(-) diff --git a/lib/scatter.js b/lib/scatter.js index 61a6d3a..23a0242 100644 --- a/lib/scatter.js +++ b/lib/scatter.js @@ -88,6 +88,24 @@ export class ResizeEvent extends BaseEvent { * * @constructor */ + +let ThrowableObjects = [] +let ThrowableRequests = null + +function stepThrowAnimation() { + let clones = [...ThrowableObjects] + ThrowableObjects = [] + for(let obj of clones) { + obj.animateThrow() + } + requestAnimationFrame(stepThrowAnimation) +} + +function startThrowableLoop() { + requestAnimationFrame(stepThrowAnimation) + return true +} + class Throwable { constructor({ movableX = true, @@ -181,6 +199,13 @@ class Throwable { return dt } + recurseAnimateThrow() { + ThrowableObjects.push(this) + if (ThrowableRequests == null) { + ThrowableRequests = startThrowableLoop() + } + } + animateThrow(time) { if (this.velocity != null) { let dt = this._throwDeltaTime() @@ -199,19 +224,11 @@ class Throwable { this.onDragUpdate(d) if (dt == 0 || this.needsAnimation()) { - if (this._requestAnimation != 0) { - console.log("cancelAnimationFrame") - cancelAnimationFrame(this._requestAnimation) - } - this._requestAnimation = requestAnimationFrame(this.animateThrow.bind(this)) + this.recurseAnimateThrow() return } else { if (this.isOutside()) { - if (this._requestAnimation != 0) { - console.log("cancelAnimationFrame") - cancelAnimationFrame(this._requestAnimation) - } - this._requestAnimation = requestAnimationFrame(this.animateThrow.bind(this)) + this.recurseAnimateThrow() return } } @@ -222,48 +239,6 @@ class Throwable { } } - animateThrowTween(time) { - if (this.velocity != null) { - let dt = this._throwDeltaTime() - // console.log("animateThrow", dt) - let next = this.nextVelocity(this.velocity) - let prevLength = Points.length(this.velocity) - let nextLength = Points.length(next) - if (nextLength > prevLength) { - let factor = nextLength / prevLength - next = Points.multiplyScalar(next, 1 / factor) - // console.log('Prevent acceleration', factor, this.velocity, next) - } - this.velocity = next - let d = Points.multiplyScalar(this.velocity, dt) - this._move(d) - this.onDragUpdate(d) - TweenMax.to(this, 0.5, { _dummy: 1, - ease: Linear.easeNone, - onComplete: () => { - if (dt == 0 || this.needsAnimation() || this.isOutside()) { - this.animateThrow() - }}}) - - - /* if (dt == 0 || this.needsAnimation()) { - - - requestAnimationFrame(this.animateThrow.bind(this)) - return - } else { - if (this.isOutside()) { - requestAnimationFrame(this.animateThrow.bind(this)) - return - } - } */ - } - this.onDragComplete() - if (this.onThrowFinished != null) { - this.onThrowFinished() - } - } - needsAnimation() { if (this.velocity == null) { return false