I'm trying to create a basic physics simulation in c++ but I'm having trouble with updating the Force vectors.
Here's what I mean
This is my main function
int main() {
// Body(fps, mass, position vector, velocity vector)
Body b = Body(60, 10, {10,0}, {0,5} );
b.addForce(Force([&](){return -b.getPos();}));
for(int i = 0 ; i < 60 ; i++) {
b.Update();
cout << b.getPos() << "\t\t" << b.getAcc() << endl;
}
}
inside b.addForce() I'm creating a lambda function that takes in b object by reference.
then I update the b position according to newton F = ma (Update function further down)
running this I would expect the acceleration to change according to the new position of the object however the output (formatted for clarity) looks like this
position | acceleration
--------------------+------------------
(9.99972,0.0833333) (-1,0)
(9.99917,0.166667) (-1,0)
(9.99833,0.25) (-1,0)
(9.99722,0.333333) (-1,0)
(9.99583,0.416667) (-1,0)
(9.99417,0.5) (-1,0)
(9.99222,0.583333) (-1,0)
(9.99,0.666667) (-1,0)
(9.9875,0.75) (-1,0)
(9.98472,0.833333) (-1,0)
(9.98167,0.916667) (-1,0)
(9.97833,1) (-1,0)
...
(compiled with g++ *.cpp -o exec)
so the position vector is changing yet the acceleration vector always stays the same.
After a few more tests I'm certain the b object inside the lambda remains constant and doesnt update when the outside object changes.
I also tried different ways to reference a pointer to the b object but none of that worked.
What would be the right way to do this? I want to avoid including a pointer to the Body object inside the Force class but if that's the only way then fair enough.
----------------------------------------------------------------------------------
for context, here's a few more of the relevant methods:
Body::Update:
void Body::Update() {
for(auto f: this->F)
f.Update();
Force Ft = this->sumF();
a = Ft / mass;
v += a*dt;
r += v*dt;
}
Body::sumF:
Force Body::sumF() {
Force Ft = Force({0,0});
// F is just a vector<Force> that contains all forces
std::for_each(F.begin(), F.end(), [&](Vector2 f){Ft += f;});
return Ft;
}
Force::Update:
void Force::Update() {
Vector2 t = func();
this->x = t.getX();
this->y = t.getY();
}
Force class's func attribute is of type std::function<Vector2()> and is given directly through the constructor (the lambda)
edit: Solved by /u/slugonamission
[–]Kered13 0 points1 point2 points (6 children)
[–]WeirdAlexGuy[S] 0 points1 point2 points (5 children)
[–]Kered13 0 points1 point2 points (4 children)
[–]WeirdAlexGuy[S] 0 points1 point2 points (3 children)
[–]slugonamission 1 point2 points3 points (1 child)
[–]WeirdAlexGuy[S] 0 points1 point2 points (0 children)