From 3a4361e5e6b98f2725c5a2b4786473f74ca953a0 Mon Sep 17 00:00:00 2001 From: Tobias Bengfort Date: Mon, 24 Sep 2018 22:06:25 +0200 Subject: [PATCH] fix air friction calculation The code is slghtliy confusing because `velocityPrevX` and `velocityPrevY` actually define a distance. The real velocity can be calculated as `velocityPrevX / deltaTimePrev` and `velocityPrev / deltaTimePrev` where `deltaTimePrev = deltaTimeScaled / correction`. This is the formular without air friction: ``` velocity.x = velocityPrevX * correction + body.force.x / body.mass * deltaTimeSquared ``` Air friction is a force that acts in the opposite direction of the velocity. It is proportional to velocity (for small velocity): ``` velocity.x = velocityPrevX * correction + (body.force.x - (body.frictionAir * velocityPrevX / deltaTimeScaled * correction)) / body.mass * deltaTimeSquared ``` which can be converted to: ``` velocity.x = velocityPrevX * (1 - body.frictionAir * deltaTimeScaled / body.mass) * correction + body.force.x / body.mass * deltaTimeSquared ``` --- src/body/Body.js | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/src/body/Body.js b/src/body/Body.js index a02647e..65cbae1 100644 --- a/src/body/Body.js +++ b/src/body/Body.js @@ -602,10 +602,11 @@ var Axes = require('../geometry/Axes'); * @param {number} correction */ Body.update = function(body, deltaTime, timeScale, correction) { - var deltaTimeSquared = Math.pow(deltaTime * timeScale * body.timeScale, 2); + var deltaTimeScaled = deltaTime * timeScale * body.timeScale; + var deltaTimeSquared = Math.pow(deltaTimeScaled, 2); // from the previous step - var frictionAir = 1 - body.frictionAir * timeScale * body.timeScale, + var frictionAir = 1 - body.frictionAir * deltaTimeScaled / body.mass, velocityPrevX = body.position.x - body.positionPrev.x, velocityPrevY = body.position.y - body.positionPrev.y;