Reputation: 59
This is probably a really stupid question but I am having trouble showing more that one copy of my class on the screen. I have created an asteroid class that generates and moves an asteroid on the screen. Yet when I try and call multiple versions of this class in my main body, it still only shows one asteroid.
Main
int lrgAsteroids = 4;
Asteroid[] asteroid = new Asteroid[lrgAsteroids];
void setup() {
size(800,800);
for (int i = 0; i < lrgAsteroids; i++) {
asteroid[i] = new Asteroid();
asteroid[i].display();
}
}
void draw() {
background(0);
asteroid[0].move();
asteroid[1].move();
for (int i = 0; i < lrgAsteroids; i++) {
asteroid[i].move();
}
}
asteroid class.
class Asteroid {
PImage lrgAsteroid;
float xpos, ypos;
float yDirection;
float xDirection;
float radians = 0;
Asteroid() {
lrgAsteroid = loadImage("largeAsteroid.png");
xpos = random(0,710);
ypos = random(0,710);
int xDir = (int) random(2);
int yDir = (int) random(2);
if (xDir == 1) {
xDirection = 1;
} else if (xDir == 0) {
xDirection = -1;
}
if (yDir == 1) {
yDirection = 1;
} else if (yDir == 0) {
yDirection = -1;
}
}
void display() {
image(lrgAsteroid, xpos, ypos);
}
void move() {
background(0);
pushMatrix();
imageMode(CENTER);
translate(xpos, ypos);
rotate(radians);
image(lrgAsteroid, 0, 0);
popMatrix();
if (xpos <= 0) {
xpos = random(750,800);
} else if (xpos >= 800) {
xpos = random(0,100);
}
if (ypos <= 0) {
ypos = random(750,800);
} else if (ypos >= 800) {
ypos = random(0,100);
}
radians += 0.02;
xpos += xDirection;
ypos += yDirection;
}
}
Any help would be greatly appreciated.
Upvotes: 1
Views: 59
Reputation: 210909
The bug is very simple. Actually the display is clear, before an asteroid is drawn, because of background(0);
in the method move()
. It is sufficient to clear the background at the begin of draw()
.
Remove background(0);
from the method move()
:
Asteroid() {
// [...]
void move() {
// background(0); <---- DELETE
pushMatrix();
imageMode(CENTER);
translate(xpos, ypos);
rotate(radians);
image(lrgAsteroid, 0, 0);
popMatrix();
if (xpos <= 0) {
xpos = random(750,800);
} else if (xpos >= 800) {
xpos = random(0,100);
}
if (ypos <= 0) {
ypos = random(750,800);
} else if (ypos >= 800) {
ypos = random(0,100);
}
radians += 0.02;
xpos += xDirection;
ypos += yDirection;
}
}
Upvotes: 1
Reputation: 871
I think that somehow all the instances that your create get the same xDir and yDir or same xpos and ypos , can you print it so you can see if that's the problem ?
void setup() {
size(800,800);
for (int i = 0; i < lrgAsteroids; i++) {
asteroid[i] = new Asteroid();
// add these please to see what happens
System.out.println(asteroid[i].xDirection+" "+asteroid[i].yDirection);
}
}
void draw() {
background(0);
asteroid[0].move();
asteroid[1].move();
for (int i = 0; i < lrgAsteroids; i++) {
asteroid[i].move();
// add these please to see what happens
System.out.println(asteroid[i].xpos+" "+asteroid[i].ypos);
}
Upvotes: 0