sub2nullexception
sub2nullexception

Reputation: 118

How calculate stopping distance from velocity and cheat's friction

I'm implementing a 2D physics game. Suppose we have vx as our velocity, and every game update we apply friction like this -

vx *= 0.99 // incredibly low friction.

How would I calculate the distance covered from our initial velocity?

Upvotes: 0

Views: 107

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30685

We can use a while loop to sum the distance traveled as the object slows down, we sum for each iteration of the loop.

It's worthwhile pointing out that the object will never completely stop, but the distance traveled will reach a limit.

We can use a velocity threshold to decide what we consider as stopped.

const friction = 0.99;
const stoppedVelocityThreshold = 0.001;

let velocity = 100;
let distance = 0;

while (velocity > stoppedVelocityThreshold) {
    distance += velocity;
    velocity *= friction;
}

console.log('Final Distance:', distance)
.as-console-wrapper { max-height: 100% !important; }

We can also view distance as an infinite geometric series of the form:

a + ar + ar² + ar³ ...

Where a = Initial velocity and r = friction.

The sum of this series is given by:

enter image description here

then use this to sum the distance after count steps.

This will converge to:

enter image description here

Distance after N steps:

const velocity = 100.0;
const friction = 0.99;
const input = [10, 100, 1000, 10000];

for(let n of input) {
    const distanceAfterNSteps = velocity * (1 - Math.pow(friction, n)) / (1 - friction);
    console.log(`Distance after ${n} steps:`, distanceAfterNSteps .toFixed(3))
}
.as-console-wrapper { max-height: 100% !important; }

Final distance:

const velocity = 100.0;
const friction = 0.99;

const finalDistance = velocity / (1 - friction);
console.log('Final distance:', finalDistance.toFixed(3))
.as-console-wrapper { max-height: 100% !important; }

Upvotes: 2

Related Questions