Can you help me understand why b = null in draw function is incorrect
import java.util.List;
import java.util.ArrayList;
spaceShip ship;
boolean left = false;
boolean right = false;
boolean forward = false;
int maxQuantity = 7;
float inercia;
ArrayList<Bolder> bmas = new ArrayList<Bolder>();
ArrayList<Integer> brem = new ArrayList<Integer>();
ArrayList<Laser> las = new ArrayList<Laser>();
PVector Rand = new PVector(random(50), random(50));
PVector shipPos;
void setup() {
size(1280, 720);
ship = new spaceShip();
shipPos = ship.pos;
for (int j = 0; j < maxQuantity; ++j) {
bmas.add(new Bolder(random( width/2, width ) * random(3), random(height/2, height) * random(3)));
}
}
void draw() {
int j =0;
background(0);
for (Laser l : las) {
l.show();
l.move();
}
ship.render();
ship.edges();
// все связанное с астеройдами
for (Bolder b : bmas) {
b.show();
b.move();
b.edges();
for (Laser l : las) {
if (b.destroy(l, b, l.pos.x, l.pos.y))
b = null;
}
++j;
}
//for (int h = 0; h < brem.size(); ++h)
//bmas.remove(brem.get(h));
//добавление новых астеройдов
if (bmas.size() < maxQuantity) {
for (int i = bmas.size(); i < maxQuantity; ++i)
bmas.add(new Bolder(random(width), random(height)));
}
}
void keyPressed() {
if (keyCode == RIGHT) {
ship.turn(0.75);
} else if (keyCode == LEFT) {
ship.turn(-0.75);
} else if (keyCode == UP) {
ship.forward(-24);
} else if (keyCode == DOWN) {
las.add(new Laser(ship.pos.x, ship.pos.y, ship.heading, -4));
}
}
1 Like
I think you need to tell the ArrayLists of which class the objects in it are:
You do this with <Bolder>
ArrayList<Bolder> bmas = new ArrayList();
ArrayList<Bolder> brem = new ArrayList();
ArrayList<Laser> las = new ArrayList();
1 Like
@Chrisir is correct on initializing ArrayLists.
Additionally, the assignment of “b = null;” in this case is only setting the local variable “b” to null.
This will not affect the contents of “bmas”.
You can verify this by adding the following after the loop:
String s = "";
for (Bolder b : bmas) {
s += b + "\n";
}
text(s, 10, 20); // will not show "null" in any of the objects listed
I recommend using a state variable inside the “Bolder” class.
For example:
b.alive = false; // initialize "alive = true;" in constructor
Then you can remove any objects that were marked “false”.
Take a look at the note about modifying an ArrayList on the reference page.
2 Likes