Arrays
in
Programming Questions
•
10 months ago
How do I get balloons to move?
Balloon [] balloons = new Balloon[30];
void setup() {
size(400, 400);
frameRate(20);
for (int i = 0; i < balloons.length; i++) {
float w = random(20, 45);
float h = w + random(5, 10);
float x = random(w/2, width-w/2);
float y = random(h/2, height-h/2);
color c = color(random(255), random(255), random(200), random(128, 200));
balloons[i] = new Balloon(x, y, w, h, c);
}
}
void draw() {
background(255);
for (int i = 0; i < balloons.length; i++) {
// Only act on balloons that have not "popped"
if (balloons[i].alive) {
balloons[i].display();
//balloons[i].move();
if (balloons[i].hit()) balloons[i].alive = false;
}
}
}
class Balloon {
// An alternative method to "pop" a balloon
boolean alive = true;
float x;
float y;
float w;
float h;
color c;
float xSpeed;
float ySpeed;
Balloon(float bx, float by, float bw, float bh, color bc) {
x = bx;
y = by;
w = bw;
h = bh;
c = bc;
xSpeed = 3;
ySpeed = 7;
}
void display() {
fill(c, 150);
ellipse(x, y, w, h);
}
boolean hit() {
float a = w / 2.0;
float b = h / 2.0;
float ex = mouseX - x; // calculate relative to center of ellipse
float ey = mouseY - y;
float r = (ex * ex) / (a * a) + (ey * ey) / (b * b);
return (r < 1);
}
/*void pop() {
x= -1000;
y= -1000;
xSpeed = 0;
ySpeed = 0;
alive = false;
}*/
void move() {
x += xSpeed;
if (x < w/2 || x > width-w/2) xSpeed = -xSpeed;
y += ySpeed;
if (y < h/2 || y > height-h/2) ySpeed = -ySpeed;
}
}
Balloon [] balloons = new Balloon[30];
void setup() {
size(400, 400);
frameRate(20);
for (int i = 0; i < balloons.length; i++) {
float w = random(20, 45);
float h = w + random(5, 10);
float x = random(w/2, width-w/2);
float y = random(h/2, height-h/2);
color c = color(random(255), random(255), random(200), random(128, 200));
balloons[i] = new Balloon(x, y, w, h, c);
}
}
void draw() {
background(255);
for (int i = 0; i < balloons.length; i++) {
// Only act on balloons that have not "popped"
if (balloons[i].alive) {
balloons[i].display();
//balloons[i].move();
if (balloons[i].hit()) balloons[i].alive = false;
}
}
}
class Balloon {
// An alternative method to "pop" a balloon
boolean alive = true;
float x;
float y;
float w;
float h;
color c;
float xSpeed;
float ySpeed;
Balloon(float bx, float by, float bw, float bh, color bc) {
x = bx;
y = by;
w = bw;
h = bh;
c = bc;
xSpeed = 3;
ySpeed = 7;
}
void display() {
fill(c, 150);
ellipse(x, y, w, h);
}
boolean hit() {
float a = w / 2.0;
float b = h / 2.0;
float ex = mouseX - x; // calculate relative to center of ellipse
float ey = mouseY - y;
float r = (ex * ex) / (a * a) + (ey * ey) / (b * b);
return (r < 1);
}
/*void pop() {
x= -1000;
y= -1000;
xSpeed = 0;
ySpeed = 0;
alive = false;
}*/
void move() {
x += xSpeed;
if (x < w/2 || x > width-w/2) xSpeed = -xSpeed;
y += ySpeed;
if (y < h/2 || y > height-h/2) ySpeed = -ySpeed;
}
}
1