0

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 Drawables?

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.

Oscar Linde
  • 518
  • 4
  • 17
  • What you usually do is that the model classes don't know anything about being drawn. Instead, you have some GUI classes that are the ones that contain your model classes and knows how to draw them. That way you can also reuse all the code in case you want to show your game in different devices, for example – xp500 Feb 16 '14 at 17:33

3 Answers3

1

You can test whether an Entity implements Drawable using the instanceof operator:

for (Entity entity : entities) {
    if (entity instanceof Drawable) {
        ((Drawable) entity).draw(g);
    }
}
Ted Hopp
  • 232,168
  • 48
  • 399
  • 521
  • Thanks! I wrote this in my question but is it really effective to have in your game-loop? – Oscar Linde Feb 16 '14 at 17:40
  • @OscarLinde - The performance hit from using `instanceof` is probably insignificant, even in the game loop. See, for instance, [this thread](http://stackoverflow.com/questions/103564/the-performance-impact-of-using-instanceof-in-java). Also, it's likely that the drawing itself is much more expensive than `instanceof`. If you have just a few `Drawable` objects in a vast sea of non-`Drawable` `Entity` objects, then [Kayaman's answer](http://stackoverflow.com/a/21814808/535871) would be a good approach. – Ted Hopp Feb 16 '14 at 17:51
1

Keep an additional collection of Drawables. That way you can limit to drawing those, and do all the other things to all Entities.

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

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.

Jason
  • 13,563
  • 15
  • 74
  • 125
  • I'm loading a tile map and i have invisible "objects" in a seperate layer. These objects determine whether i have collided somewhere or not. They don't neccesarily have to be the size of the tile they're on, and are therefore invisible. – Oscar Linde Feb 16 '14 at 17:43