UNPKG

@rpgjs/physic

Version:

A deterministic 2D top-down physics library for RPG, sandbox and MMO games

75 lines (74 loc) 2.34 kB
function applyConstantForce(entity, force) { entity.applyForce(force); } function applyAttraction(entity, target, strength, maxDistance) { const direction = target.sub(entity.position); const distance = direction.length(); if (maxDistance !== void 0 && distance > maxDistance) { return; } if (distance < 1e-3) { return; } direction.normalizeInPlace(); const force = direction.mul(strength); entity.applyForce(force); } function applyRepulsion(entity, source, strength, maxDistance) { const direction = entity.position.sub(source); const distance = direction.length(); if (maxDistance !== void 0 && distance > maxDistance) { return; } if (distance < 1e-3) { return; } direction.normalizeInPlace(); const force = direction.mul(strength); entity.applyForce(force); } function applyDirectionalForce(entity, direction, strength) { const normalized = direction.normalize(); const force = normalized.mul(strength); entity.applyForce(force); } function applyExplosion(entity, center, strength, radius, falloff = 1) { const direction = entity.position.sub(center); const distance = direction.length(); if (distance > radius || distance < 1e-3) { return; } const normalizedDistance = distance / radius; const forceStrength = strength * Math.pow(1 - normalizedDistance, falloff); direction.normalizeInPlace(); const force = direction.mul(forceStrength); entity.applyImpulse(force); } function applySpring(entityA, entityB, restLength, springConstant, damping) { const direction = entityB.position.sub(entityA.position); const distance = direction.length(); if (distance < 1e-3) { return; } const displacement = distance - restLength; const springForce = springConstant * displacement; direction.normalizeInPlace(); const force = direction.mul(springForce); entityA.applyForce(force.mul(-1)); entityB.applyForce(force); if (damping > 0) { const relativeVelocity = entityB.velocity.sub(entityA.velocity); const dampingForce = direction.mul(-damping * relativeVelocity.dot(direction)); entityA.applyForce(dampingForce.mul(-1)); entityB.applyForce(dampingForce); } } export { applyAttraction, applyConstantForce, applyDirectionalForce, applyExplosion, applyRepulsion, applySpring }; //# sourceMappingURL=index9.js.map