javaprocessingcollisiongravityenergy

Gravitational attraction and collision


I made a simple program that simulates how a round object would behave with a roudn surface in an environment with gravity and collision.

My problem is related with the application of gravity: whenever an object get's very close to the attractor it starts reegaining height, what I think is causing the issue is that, let's say that the ball is touching the ground with very low speed, my program applies gravity and, sicne it will make contact, reverses the force and sends it into the air again.

I tried stopping the ball once it reached low enough speed, but the effect is overall unpleasing (it never is slow enough to make it seemless)

This is the code, what do you thin kis the mistake? As I listed only part of the code and it's pretty complciated I don't expect a specific response, but where do you think the issue could generally lie? My guess is that I didn't respect the kinetic/potential energy relation, but I wouldn't know how to make it right either :/

    void update(ArrayList<Attracter>a) {
    pos.add(acceleration);
    println(acceleration.mag());
    for (Attracter ar : a)
      if (PVector.dist(pos, ar.pos)<ar.size/2+size/2) { 
        
        //send the compenetrated body back

        float difference=((ar.size/2+size/2)-PVector.dist(pos, ar.pos)+1);
        pos.sub(acceleration.copy().normalize().mult(difference));  
        
        //calculate the new acceleration
        PVector perpendicular= PVector.sub(pos,ar.pos).normalize(); //perpendicolare
        float angle=perpendicular.rotate(-PI/2).heading();//angolo dellatangente
        perpendicular.rotate(-angle); //normalizzo l'angolo
        acceleration.rotate(-angle); //normalizzo l'accellerazione
        
        PVector newAcceleration= PVector.fromAngle(perpendicular.heading()-acceleration.heading());
        acceleration=newAcceleration.setMag(acceleration.mag());
        acceleration.rotate(angle); //denormalizzo l'accellerazione
          
        //push the body forward
        pos.add(acceleration.copy().normalize().mult(difference));
        acceleration.mult(0.9); 
        }
  }

Solution

  • Remove the +1 in the difference calculation, i.e. try to replace

    float difference=((ar.size/2+size/2)-PVector.dist(pos, ar.pos)+1);
    

    with

    float difference=((ar.size/2+size/2)-PVector.dist(pos, ar.pos));