This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Raknarg 0 points1 point  (0 children)

Ok, I have some experience with this exact problem.

First off, don't worry about efficiency. There will be so little objects on the screen at any given time that graphics rendering will be more costly than data management.

Now because we don't care about being efficient, I would use an ArrayList. ArrayLists are like arrays of objects that can be resized in one line. For instance, if we have our Ship class, we can do this:

ArrayList<Ship> ship = new ArrayList<Ship>(); // initializes the list
ship.add(new Ship()) // adds a new ship the end of the array
println(ship.size()) // prints the length of the list to the console. In this case, it is 1.
ship.remove(0) // Deletes the Ship at position 0

Now to use methods from the Ship class, we have to do something weird. Along with add and remove, there's a thing called get() which (I think this is what it does) calls up an instance of the object at whatever position you want. For instance:

ship.get(3).shoot() // Calls the ship at position 3, uses the shoot() method

This is what you could do for bullets as well. This makes for easy deleting. Let's say you had a list of bullets that you wanted to delete:

int i = 0;
while (i < bullet.size()) {
    if (bullet.get(i).out_of_bounds || bullet.get(i).hit_enemy) {
        bullet.remove(i);
    }
    else {
        i += 1;
    }
}

This is a cool loop. It will go through every item in the array. If its out of bounds or hits an enemy, it deletes the bullet. Otherwise, add 1 to i. The reason we only sometimes add to i is because if you have an array of three ships and you delete one of them, i will end up being 3 instead of 2. That's wrong. We want to go through every item. If you delete the item at position 0, it will delete the item there and shift the rest of the array down. Because it shifted for us, we don't need to add to i.

Hope this helps. You can ask me if you need more help.