class Mass
{
public:
Mass (double mass = 1, const Vector2D& friction = 0): m(mass), f(friction) {}
Vector2D get_pos () const { return pos; }
void apply (Vector2D force)
{
this->force += force;
}
void reset ()
{
force.x = 0;
force.y = 0;
}
void simulate (long double dt)
{
vel += (force / m) * dt;
if (vel != 0) {
vel -= f * dt;
}
pos += vel * dt;
}
private:
double m;
Vector2D f;
Vector2D pos;
Vector2D vel;
Vector2D force;
};
Vector2D is a simple implementation of a vector that defines all the necessary operators, adapted from the tutorial. My game code looks like this:
Mass obj(1, Vector2D(0.5, 0.5));
double dt = 0.1 / 60;
while (!done) {
obj.reset();
if (myWin.checkKey(VK_RIGHT)) { // checks if a given key was pressed.
obj.apply(Vector2D(4, 0));
}
obj.simulate(dt);
displayScene(myWin, (float)obj.get_pos().x, (float)obj.get_pos().y); // implementation not important
}
Now my issue is that once the object starts moving right, it slows down until it stops, then begins moving left. I'm sure it's to do with my implementation of friction:if (vel != 0) {
vel -= f * dt;
}
It doesn't stop subtracting once velocity reaches 0 because it's never precisely 0. It also would not work correctly if I tried to move my object left. However, I'm not really sure how to approach this problem. Can anybody with more game programming experience give me a hand?Thanks for your time.
Edit: I found a solution:
vel /= 1 + f * dt;
Simple .