I’m trying to write a 2d ball pit simulation using verlet integration.
But I’m having trouble accessing the other balls while looping through them.
In the section commented “//collide the balls” I’m trying to access the other balls but it seems to return true everytime and all the balls instantly turn white, I think the issue might be that I’m accessing the other balls in the array wrong.
Any help would be appreciated!
Particle[] balls = new Particle[100];
float mapSize;
void setup() {
size(640, 640);
mapSize = min(width, height)-32;
noStroke();
colorMode(HSB, 360, 100, 100);
for(int i=0; i<balls.length; i++) {
balls[i] = new Particle(random(100, width-100), random(100, height-100), color(random(0, 360), 100, 100), 10);
}
}
void draw() {
background(64);
fill(0);
ellipse(width/2, height/2, mapSize, mapSize);
for(int i=0; i<balls.length; i++) {
balls[i].updateSpeed();
}
for(int i=0; i<balls.length; i++) {
balls[i].updatePosition();
}
for(int i=0; i<balls.length; i++) {
balls[i].collision();
}
for(int i=0; i<balls.length; i++) {
balls[i].display();
}
}
class Particle {
float posX;
float posY;
float speedX;
float speedY;
color c;
float diameter;
float PposX;
float PposY;
Particle(float posXTemp, float posYTemp, color colorTemp, float diameterTemp) {
posX = posXTemp;
posY = posYTemp;
PposX = posXTemp + random(-10, 10);
PposY = posYTemp + random(-10, 10);
c = colorTemp;
diameter = diameterTemp;
}
void updateSpeed() {
//calculate speed
speedX = posX - PposX;
speedY = posY - PposY;
//apply gravity to speed
speedY = speedY + 0.1;
}
void updatePosition() {
//store old position
PposX = posX;
PposY = posY;
//calculate new position
posX = posX + speedX;
posY = posY + speedY;
}
void collision() {
//move position back into bounds
if(dist(posX, posY, width/2, height/2) > (mapSize/2)-(diameter/2)) {
float outOfBoundsDist = ((dist(posX, posY, width/2, height/2) - (mapSize/2))+(diameter/2)) / mapSize;
posX = lerp(posX, width/2, outOfBoundsDist*1.6);
posY = lerp(posY, height/2, outOfBoundsDist*1.6);
}
//collide the balls
for(int j=0; j<balls.length; j++) {
if(dist(balls[j].posX, balls[j].posY, posX, posY) < (diameter/2) + (balls[j].diameter/2)) {
c = color(0, 0, 100);
}
}
}
void display() {
fill(c);
ellipse(posX, posY, diameter, diameter);
}
}