Search code examples
c++mathreductionsimplification

Is there a more elegant/clever/brief way to bring an unknown number closer to 0?


Basically I'm working out drag in a game with physics. The sideways motion needs to be reduced (as in brought closer to 0, not just brought into negative), but I don't know which direction it's travelling in, so I don't know whether to add drag or subtract drag.

(If an item is moving right, it has positive force, moving left, negative force)

Right now I'm doing this:

if (objects[i]->force.x > 0)
    objects[i]->force.x -= drag;
else
    objects[i]->force.x += drag;

Which works fine, but I get the feeling that there's bound to be a sleeker way to do this.

It also couldnt hurt to find a way to ensure it doesn't go past 0


Solution

  • If you are trying to emulate friction, the easiest way, is to know the velocity and use a mathematical model, or differential equation to approximate it.

         dx
    -c * --
         dt
    

    basically, the force of friction is proportional to the velocity and in opposite direction. Thus, you can calculate the force of friction (or drag) simply as follows:

    objects[i]->force = -drag_coefficient * objects[i]->velocity
    

    If you do not know the velocity, it gets difficult to get good results, as you may have a force pushing right, while the object is moving left (therefore you would apply drag to the wrong direction).

    Edit:

    Actually, not all kinds of friction depend on the magnitude (speed) of the velocity, dry friction is often referred as just taking the direction of the velocity into account:

    force = -drag_coefficient * sign(velocity)
    

    However computationally this becomes unstable as velocity reaches 0, overshoots it and oscillates back and forth.

    Another model is the one for wet friction, that is the one I used in the first example:

    force = -drag_coefficient * velocity
    

    This means that as your object is running faster, it will be slowed down more by friction. Think for example of the force of air, as you are running, the faster you are running, the more the air is trying to slow you down.

    Neither of the models above is 100% accurate, but for a game they should be more than enough