Bolas que reboten cuando se chocan: array de objetos
int N = 8;
Pelota[] pelotas;
void setup() {
size(800, 600);
frameRate(300);
pelotas = new Pelota[N];
for (int i = 0; i < N; i++) {
float r = random(15, 40);
pelotas[i] = new Pelota(random(r, width - r), random(r, height - r), random(-2, 2), random(-2, 2), r);
}
}
void draw() {
background(220);
for (int i = 0; i < N; i++) {
pelotas[i].mover();
pelotas[i].rebotar();
pelotas[i].dibujar();
}
for (int i = 0; i < N; i++) {
for (int j = i + 1; j < N; j++) {
pelotas[i].choque(pelotas[j]);
}
}
}
class Pelota {
float x, y;
float dx, dy;
float r;
Pelota(float Tx, float Ty, float Tdx, float Tdy, float Tr) {
x = Tx;
y = Ty;
dx = Tdx;
dy = Tdy;
r = Tr;
}
void mover() {
x = x+dx;
y = y+dy;
}
void rebotar() {
if (x - r < 0 || x + r > width) {
dx = dx*-1;
}
if (y - r < 0 || y + r > height) {
dy = dy*-1;
}
}
void dibujar() {
ellipse(x, y, r * 2, r * 2);
}
void choque(Pelota otra) {
float d = dist(x, y, otra.x, otra.y);
if (d <= r + otra.r) {
float tx = dx;
float ty = dy;
dx = otra.dx;
dy = otra.dy;
otra.dx = tx;
otra.dy = ty;
}
}
}
Comentarios
Publicar un comentario