Search code examples
c++simulationphysicsglm-math

Weird behaivour when trying to simulate gravity


I'm trying to simulate Newtonian gravity with C++ and GLM. I'm using GLM vectors and this equation I found on Wikipedia

I translated this into code:

const static double g_const = 6.67430E-11;
void gravitate(object& obj1,object& obj2) {
    glm::vec2 distance = glm::abs(obj2.position-obj1.position);
    glm::vec2 unitvec = (obj2.position-obj1.position)/distance;
    glm::vec2 force = -g_const*obj1.mass*obj2.mass/(distance*distance)*unitvec;
    obj2.updateForce(force);
}

The object class is structured as this

class object {
public:
    double mass;
    glm::vec2 velocity;
    glm::vec2 position;

    object(double massin, glm::vec2 pos) : mass(massin), position(pos) {;}
    object(double massin, glm::vec2 pos, glm::vec2 vel) : mass(massin), position(pos), velocity(vel) {;}

    void updateForce(glm::vec2 force) {
        velocity+=force/mass;
    }

    void updatePos() {
        position+=velocity;
    }

    void printPos(); // Not used in this example
    void printVel(); // Not used in this example
}

The main function is run like this:

int main() {
    object test1(massOfEarth,
        glm::vec2(0, 0),
        glm::vec2(0,0));
    object test2(massOfmoon,
        glm::vec2(distanceFromEarth,
        distanceFromEarth),
        moonInitalVelocity);
    while (true) {
       gravitate(test1,test2);
       test2.updatePos();
    }
}

When I run this, however, I get this output: GIF Version

NOTE: Sorry for the low frame rate, it's a byproduct of converting a video to a GIF

Does anyone know what's going wrong here?

BTW the full code is available here: https://github.com/ProtoByter/GravityLaw

EDIT 1:

The y force placed on the object at the point that it suddenly speeds up is 3.5079064080620432e+26 N

whilst when it's moving at a constant speed the y force is -2.9308778146655032e+23 N

EDIT 2:

For clarification I'm using the vector form of newton's universal law of gravity, on wikipedia this is defined as a vector quantity whilst glm::distance returns a double so is not suitable


Solution

  • You using wrong function for Calculating the distance between the two objects, You have used glm::abs(gentype const &x) which is just for calculating the absolute value of x, i.e. if x < 0 then it returns -x and if x >= it simply returns as it is.

    You can used glm::distance(point1, point2) for calculating the distance between the point1 and point2.

    for more information you can check out this link: https://glm.g-truc.net/0.9.4/api/a00129.html and https://glm.g-truc.net/0.9.4/api/a00131.html