@rpgjs/physic
Version:
A deterministic 2D top-down physics library for RPG, sandbox and MMO games
44 lines (43 loc) • 1.32 kB
JavaScript
class Knockback {
/**
* Creates a knockback movement.
*
* @param direction - Direction of the impulse (will be normalized)
* @param initialSpeed - Initial speed in units per second
* @param duration - Duration in seconds
* @param decayFactor - Fraction of speed preserved per second (0-1)
*/
constructor(direction, initialSpeed, duration, decayFactor = 0.35) {
this.duration = duration;
this.decayFactor = decayFactor;
this.elapsed = 0;
const magnitude = Math.hypot(direction.x, direction.y);
this.direction = magnitude > 0 ? { x: direction.x / magnitude, y: direction.y / magnitude } : { x: 1, y: 0 };
this.currentSpeed = initialSpeed;
}
update(body, dt) {
this.elapsed += dt;
if (this.elapsed <= this.duration) {
body.setVelocity({
x: this.direction.x * this.currentSpeed,
y: this.direction.y * this.currentSpeed
});
const decay = Math.max(0, Math.min(1, this.decayFactor));
if (decay === 0) {
this.currentSpeed = 0;
} else if (decay === 1) ;
else {
this.currentSpeed *= Math.pow(decay, dt);
}
} else {
body.setVelocity({ x: 0, y: 0 });
}
}
isFinished() {
return this.elapsed >= this.duration;
}
}
export {
Knockback
};
//# sourceMappingURL=index35.js.map