I am developing a simple 2D game in Java and I'm stuck.
All my game objects( Enemy
, Player
, Item
, Wall
, ...) are extending Entity
.
Entity
is an abstract class containing some abstract methods like update()
.
I have made an interface called Drawable
which contains a draw()
method.
Some game objects like Item
should be an Entity
but also be Drawable
while others, like Wall, should just be an Entity
(not connected to a tile, just x and y coordinates)
It all looks something like this:
List<Entity> entities;
In constructor i do this:
entities = tileMapReader.getEntities();
My question is: How should i draw my Drawable
s?
I want to be able to do something like this:
for (Entity entity : entities) {
entity.draw(g);
}
But since all Entities don't have the draw()
method I can't do that. And i don't think if (entity instanceof Drawable)
is such a good idea.
You can test whether an Entity
implements Drawable
using the instanceof
operator:
for (Entity entity : entities) {
if (entity instanceof Drawable) {
((Drawable) entity).draw(g);
}
}
Keep an additional collection of Drawables. That way you can limit to drawing those, and do all the other things to all Entities.
First, your walls are invisible? Second, I like the other two answers: You can either keep a collection of Drawables, or check to see if that one implements Drawable.
A third option would be to have all entities implement drawable and leave the Wall's implementation blank.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.