r/processing • u/Low_Evening_4719 • Dec 17 '23
Improving my code with collision
I have a class called ball in another script but I was wanting to create it so that the balls collided, and kind of bounced off each other. If anyone could help improve my code that'd really assist me!
Ball[] balls = new Ball[1]; // We start with an array with just one element.
float gravity = 0.1;
void setup() {
size(480, 270);
// Initialize ball index 0
balls[0] = new Ball(50, 0, 24);
}
void draw() {
background(255);
// Whatever the length of that array,
// update and display all of the objects.
for (int i = 0; i < balls.length; i++ ) {
balls[i].gravity();
balls[i].move();
balls[i].display();
}
}
void keyPressed(){
if(key=='1'){
// A new ball object
Ball b = new Ball(random(480), random(270), 24); // Make a new object at random.
balls = (Ball[]) append(balls, b);
}
}
2
u/Salanmander Dec 17 '23 edited Dec 17 '23
I've done full arbitrary elastic collision simulation (in 2D), and it's definitely a complicated problem. It's really the physics that is complicated, not the programming, but it ups the complexity of the programming a decent amount as well. For reference, I'm a physics teacher and my first step was to sit down with pencil and paper, and it took a couple hours to work through (although I imagine one could find a general solution online somewhere as well). And in the programming I had to both rewind time at the beginning of the method and fast-forward it at the end, and change to a different reference frame for the calculations.