Thanks for the help... I'm still floundering around though, I think because I basically don't understand objects yet. The code is now:
Code:
int numBalls = 12;
float spring = 0.25;
float gravity = 0.2;
float friction = -0.9;
ArrayList balls;
//Ball[] balls = new Ball[numBalls];
void setup()
{
size(640, 200);
noStroke();
smooth();
balls = new ArrayList();
for (int i = 0; i < numBalls; i++) {
// balls[i] = new Ball(random(width), random(height), random(20, 40), i, balls);
balls.add(new Ball(random(width), random(height), random(20, 40), i, balls));
}
}
void draw()
{
background(0);
for (int i = balls.size() - 1; i>= 0; i--) {
Ball ball = (Ball) balls.get(i);
ball.collide();
ball.move();
ball.display();
// balls[i].collide();
// balls[i].move();
// balls[i].display();
}
}
class Ball {
float x, y;
float diameter;
float vx = 0;
float vy = 0;
int id;
ArrayList others;
Ball(float xin, float yin, float din, int idin, ArrayList oin) {
x = xin;
y = yin;
diameter = din;
id = idin;
others = oin;
}
void collide() {
for (int i = id + 1; i < balls.size() ; i++) {
float dx = others.get(i).x - x;
float dy = others.get(i).y - y;
float distance = sqrt(dx*dx + dy*dy);
float minDist = others.get(i).diameter*0.5 + diameter*0.5;
if (distance <= minDist) {
float angle = atan2(dy, dx);
float targetX = x + cos(angle) * minDist;
float targetY = y + sin(angle) * minDist;
float ax = (targetX - (Ball) others.get(i).x) * spring;
float ay = (targetY - (Ball) others.get(i).y) * spring;
vx -= ax;
vy -= ay;
others.get(i).vx += ax;
others.get(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;
}
}
void display() {
fill(255, 204);
ellipse(x, y, diameter, diameter);
}
}
void mousePressed() {
balls.add(new Ball(random(width), random(height), random(20, 40), numBalls, balls));
}
I tried it with (Ball) others.get(i) everywhere instead of just others.get(i) but got "misplaced construct" when it got to
Code: (Ball) others.get(i).vx += ax;
The error I'm getting now is "x cannot be resolved or is not a field" for this line:
Code:
float dx = others.get(i).x - x;