Delete this post.
Delete this post.
Hi,
Please format your code before posting. You can still edit your previous post to format the code.
Before answering some of your questions, there are some typos in your code.
ArrayList<Bullet> bullets = new ArrayList<Bullet();
i--
z2
and r2
that does not existNow to get to your question, let’s focus on why the bullet disappear. When you hit space, a new bullet is created.
void keyPressed() {
if (key ==' ') {
Bullet bullet = new Bullet(ship.x, height);
bullets.add(bullet);
}
...
}
As you can see, the bullet is added to the bullets
arrayList.
Now, how do they appear on screen? Well for that, we need to look at the draw()
function:
void draw() {
...
for (Bullet b : bullets) {
b.display();
...
}
...
}
As you can see, we are looping through all the bullets that are in the bullets
arrayList and for each one of them you are calling their display()
function
Now, if you want to get rid of one, the only thing you need to do is to remove them from the array because if it is not in the array anymore, you won’t be displaying it anymore. That’s what the following piece of code is doing:
void draw() {
...
for (int i = bullets.size() - 1; i >= 0; i--) {
Bullet b = bullets.get(i);
if (b.toDelete) {
bullets.remove(i); // Here we remove the bullet from the list
}
}
}
It would work the same for your invaders. The only problem right now is that you are using a fixed sized array to store your invaders Invader[] invaders = new Invader[6];
What you want to do is to store them in an arrayList
so you can add and remove invaders easily.
Creating multiple levels is another story and as people uses to say on this forum, divide to conquer! Try to implement that part and then you can move on to the next step.
Thank very much that you took your time to explain this to me it really helps me a lot.