Will
Will

Reputation: 179

How do I make an Arraylist accessible to many classes?

I'm making a vertical shooter game and I am having trouble with collision detection. Collisions are detected through the Rectangle method "intersect", but in order to keep track of everything that could collide, I need Arraylists to keep track of all the bullets and enemy ships. The Enemy and Player class both spawn Bullets (which also have there own class) so I would like to have 2 different Arraylists in my GameView class (which controls the games graphics and hopefully collisions when I'm done here).

What would be the most efficient way to allow the Bullets to be added to their respective ArrayLists upon being spawned?

Bullet class:

public class Bullet extends Location{
    private Fights bulletOwner;
    private int damage;
    private int velocity;

    public Bullet(Fights owner, int dmg, Rectangle loca)
    {
        super(loca);
        bulletOwner = owner;
        damage = dmg;
    }

    public Fights getOwner(){return bulletOwner;}
    public int getDamage(){return damage;}
    public int getVelocity(){return velocity;}

}

Location class

import java.awt.Rectangle;

public class Location {
    protected Rectangle loc;

    public Location (Rectangle location)
    {
        loc = location;
    }

    public Rectangle getLocation()
    {
        return loc;
    }

    public void updateLocation(Rectangle location)
    {
        loc = location;
    }
}

Upvotes: 4

Views: 956

Answers (2)

Andrew
Andrew

Reputation: 617

Like Marcelo said a GameState class is a good idea. I would add that making the GameState class implement the Singleton pattern would increase safety and reduce error-prone globalization of your lists. (Would have put this as a comment to the other answer, but I can't comment yet, sorry.)

Also, since your question asks about efficiency of spawning bullet objects, take a look at the Prototype and Factory patterns.

Upvotes: 1

Marcelo
Marcelo

Reputation: 11308

You can have a GameState class that has the arraylist of locations and pass the GameState instance as an argument to the constructor of the Location derived classes.

Upvotes: 2

Related Questions