Search code examples
c++physicssimulationparticles

Particle system physics acting weird


My particle system's physics update function seems to be incorrect. I'm aiming for all the particles to be attracted towards the mouse.

The particles move towards the mouse pointer just as expected, until they go very near. When they are near, they speed up so much, that they fly far away from the pointer and never return.

Here's the update function:

void updateParticle(particle& p,double time){
    const double G=0.000000000066726;
    const double POINTERMASS=1000000000000;

    double squareDistance=pow(p.coords.x-pointerDevice.x,2)+pow(p.coords.y-pointerDevice.y,2)+pow(p.coords.z-pointerDevice.z,2);
    if(squareDistance<0.001)
        squareDistance=0.001;//to fix the possible division by zero

    coords_3d_f accelerationVector={p.coords.x-pointerDevice.x,p.coords.y-pointerDevice.y,p.coords.z-pointerDevice.z};

    accelerationVector=vector_scalar_multiplication(vector_unit(accelerationVector),((G*POINTERMASS)/squareDistance));
    accelerationVector=vector_scalar_multiplication(accelerationVector,time);

    p.velocity=vector_addition(p.velocity,accelerationVector);

    p.coords.x-=p.velocity.x*time;
    p.coords.y-=p.velocity.y*time;
    p.coords.z-=p.velocity.z*time;
}

When the squareDistance is constant, the program looks OK, but I know it's false.

So, what am I doing wrong?


Solution

  • Force is inversely proportional to the square of the distance, so as the distance approaches 0, force (and acceleration) approach infinity. In other words, if the particles get very close, they also get very fast.

    If you want to be physically accurate, make your pointer-object have a finite size, so that particles bounce off of it.

    If you don't need to be accurate, you can make the force decrease when the particles are very close.