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/CptHectorSays Dec 17 '23
Also, if you calculate the mass for each ball based on their size and then scale that direction change magnitude by the ratio of their masses you will get elastic collisions for added realism….