Problem in making two balls bounce eachother

Hi there! I am trying to make two balls bounce once they hit each other, but for some reason, they are being thrown away insanely fast! My calculations are based on linear momentum conservation and a fixed coefficient of restitution.
Here is my sample:

Ball[] balls = new Ball[2];
float gravity = 0.1;
float sz;

void setup() {
 size(400, 400);
 // Initialize ball index 0
 balls[0] = new Ball(width/2 + 15, height/2, 0.04*height, 0, 0);
 balls[1] = new Ball(width/2, height/3, 0.03*height, 0, 0);
}

void draw() {
 background(100);
 // Update and display all balls
 balls[0].checkCollision(balls[1]);
 for (int i = 0; i < balls.length; i++) {
 balls[i].gravity();
 balls[i].move();
 balls[i].display();
 }
 
}

class Ball {
  PVector pos;
  PVector speed;
  float w;
  float m;
  
  Ball(float tempX, float tempY, float tempW, float xSpeed, float ySpeed) {
    pos = new PVector(tempX, tempY);
    w = tempW;
    speed = new PVector(xSpeed, ySpeed);
    m = w*w*.1;
  }
  
  void gravity() {
    // Add gravity to speed
    speed.y += gravity;
  }
  void move() {
    // Add speed to y location
    pos.add(speed);
    // If square reaches the bottom or the side
    // Reverse speed
    if (pos.y > height - w) {
      speed.y *= -0.95;
      pos.y = height - w;
    }
    if (pos.x < w) {
      speed.x *= -0.95;
      pos.x = w;
    }
    if (pos.x > height - w) {
      speed.x *= -0.95;
      pos.x = height - w;
    }
    if (pos.y < w) {
      speed.y *= -0.95;
      pos.y = w;
    }
  }
  void display() {
    // Display the circle
    fill(255);
    noStroke();
    ellipse(pos.x, pos.y, 2*w, 2*w);
  }
  
  void checkCollision(Ball other) {
    if (PVector.dist(pos, other.pos) < w + other.w) {
      
      float d = w + other.w - PVector.dist(pos, other.pos);
      PVector dist = PVector.sub(other.pos.copy(), pos.copy());
      PVector v_1 = dist.copy().setMag(PVector.dot(dist, speed));
      PVector v_2 = dist.copy().setMag(PVector.dot(dist.mult(-1), other.speed));
      speed.sub(v_1);
      other.speed.sub(v_2);
      pos.add(dist.copy().mult(-1).setMag(d/2));
      other.pos.add(dist.copy().setMag(d/2));
      
      float e = 1;
      
      PVector v_3 = PVector.div(PVector.add(PVector.mult(v_1.copy(), m - e * other.m), PVector.mult(v_2.copy(), other.m * (e + 1))), m + other.m);
      PVector v_4 = PVector.div(PVector.add(PVector.mult(v_1.copy(), m * (e + 1)), PVector.mult(v_2.copy(), other.m - e * m)), m + other.m);
      
      
      speed.add(v_3);
      other.speed.add(v_4);
    }
  }
}

The problem is on the fuction ‚ÄúcheckCollision‚ÄĚ on the 70th line. I will still work on this code for a while, but I am not finding the cause of the supersonic repulsion of the balls.
Thanks for your attention :smiley:.

1 Like

NVM, PROBLEM SOLVED!!!

I forgot to normalize the dist vector. Everything is working fine!!

1 Like