I'm developing a small space shooter game. It's a fun way to learn JAVA and I want to make sure I'm doing things correctly. This object (ship) is spawning other objects during runtime (lasers). (ship -> lasers).
I've implemented things this way:
- Object Ship is drawn on the screen. When touch is detected it's creating new instances of the class Laser then it adds them to the static LinkedList lasers inside of the GameScreen class.
- GameScreen object is in charge of drawing and updating all the lasers, ships, and effects on the screen.
Self explanatory. But now:
- detectCollision() is called and all the lasers that are intersecting ship objects are getting deleted from the LinkedList lasers.
- at the end of the game (user quits) I iterate through all the instances of the Laser class that are stored in GameScreen.lasers linked list and set all of them to null. When finished I also set the list to null.
Is this the correct way of releasing allocated memory?
Laser creation:
abstract class Ship {
if (canShoot()) {
Laser laser = new Laser(new Rectangle(x, y, width, height)); // bounds
GameScreen.playerLasers.add(laser);
}}
Laser disposal:
public class GameScreen {
private void dispose() {
for (Laser laser : playerLasers) {
laser.bounds = null;
laser = null;
}
playerLasers = null;
}}
GameScreen class collisionDetection():
public class GameScreen {
private void detectCollision() {
ListIterator<Laser> itr = playerLasers.listIterator();
while (itr.hasNext()){
Laser laser = itr.next();
if (laser.bounds.overlaps(ship.bounds)){
ship.health -= laser.damage;
laser.bounds = null;
laser = null;
itr.remove();
}}}}