Moving Balls & Shape Intersection

Hi!
I am trying to find a way to bounce balls off a shape, but I am struggling to do so. I have included an expression at the end of the ‘void move()’ component, but with no success. Any help would be greatly appreciated, thanks!

int numBalls = 50;
int numLines = 1;
Ball[] balls = new Ball[numBalls];
Dam dam;

void setup() {
  size(640, 360);
  for (int i = 0; i < numBalls; i++) {
    balls[i] = new Ball(random(0, width), random(height/2, height), 25, i, balls);
  }
  dam = new Dam();
}

void draw() {
  background(255);
  for (int i = 0; i < numBalls; i++) {
    balls[i].collide();
    balls[i].move();
    balls[i].display();
  }
  dam.damdisplay();
}

class Ball {
  float spring = 0.05;
  float gravity = 0.1;
  float friction = -0.9;
  float x;
  float y;
  float diameter;
  float vx = 0;
  float vy = 0;
  int id;

  Ball[] others;
  Ball(float xin, float yin, float din, int idin, Ball[] oin) {
    x = xin;
    y = yin;
    diameter = din;
    id = idin;
    others = oin;
  } 

  void collide() {
    for (int i = id + 1; i < numBalls; i++) {
      float dx = others[i].x - x;
      float dy = others[i].y - y;
      float distance = sqrt(dx*dx + dy*dy);
      float minDist = others[i].diameter/2 + diameter/2;
      if (distance < minDist) { 
        float angle = atan2(dy, dx);
        float targetX = x + cos(angle) * minDist;
        float targetY = y + sin(angle) * minDist;
        float ax = (targetX - others[i].x) * spring;
        float ay = (targetY - others[i].y) * spring;
        vx -= ax;
        vy -= ay;
        others[i].vx += ax;
        others[i].vy += ay;
      }
    }
  }

  void move() {
    vy += gravity;
    x += vx;
    y += vy;
    if (x + diameter/2 > width) {
      x = width - diameter/2;
      vx *= friction;
    } else if (x - diameter/2 < 0) {
      x = diameter/2;
      vx *= friction;
    }
    if (y + diameter/2 > height) {
      y = height - diameter/2;
      vy *= friction;
    } else if (y - diameter/2 < 0) {
      y = diameter/2;
      vy *= friction;
    }
    d = dist(x, y, quad(x, y));
    if (d < diameter/2) {
      vx = -vx;
    }
  }

  void display() {
    stroke(0, 0, 255);
    strokeWeight(1);
    fill(135, 206, 250);
    ellipse(x, y, diameter, diameter);
  }
}

class Dam {
  void damdisplay() {
    stroke(0, 0, 0);
    strokeWeight(3);
    fill(80, 80, 80);
    quad(width/3, height/2, width/2, height/2, width*0.667, height, width/3, height);
  }
}

1 Like

similar topic may help you
https://discourse.processing.org/t/irregular-shapes-collision-detection/

1 Like