I have an array list as such:
private List<GameObject> gameObjects = new CopyOnWriteArrayList<GameObject>();
GameObject
can be one of 3 classes: Spaceship
, Beam
and Asteroid
. They all are similar so I keep them in one array. However spaceships have addition method shoot which is used every 100ms in other thread (which is called ShootRunnable
). So I would like to iterate in it only over Spaceship
because other doesnt implement shoot method. What is the best way to achieve this?
for (GameObject ob : gameObjects) {
if (ob instanceof Spaceship) {
ob.shoot();
}
}
Can I iterate over it using something like the above? Just with the use of a cast or something? Please help.
The path you're on is technically feasible, though a good rule of thumb is that if you start using reflection, you're probably doing something wrong. In this case, it might be wisest to have a two collections, one for all your game types, and one specifically for spaceships.
In your game, are there any other actions that happen periodically?
If so, you could change the shoot()
method into an abstract method (could be named periodicAction()
) and place it in the GameObject
class. The Spaceship
class would implement this method by shooting, the other class with its specific periodic behavior and the Asteroid
class by doing nothing.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With