How to make Arraylist available to many classes?

I am making a vertical shooter game, and I am having trouble detecting collisions. Collisions are detected using the Rectangle method "intersect", but in order to track everything that might collide, I need arraists to keep track of all bullets and enemy ships. The Enemy class and Player also spawn Bullets (which also have their own class), so I would like to have 2 different Arraylists in the GameView class (which controls the graphics of the games and hopefully collisions when I finish here).

What would be the most efficient way to add bullets to the corresponding ArrayLists when they are created?

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; } } 
+4
source share
2 answers

You can have a GameState class that has a location arrealist and pass a GameState instance as an argument to the location-based class constructor.

+2
source

Like Marcelo, the GameState class is a good idea. I would add that creating a GameState class using the Singleton template will increase security and reduce the risk of globalization errors in your lists. (I would put this as a comment on another answer, but I can not comment, sorry.)

Also, since your question asks about the effectiveness of the appearance of bullet objects, take a look at the Prototype and Factory samples.

+1
source

All Articles