I am in the process of making a game, and in that process I have come across a bit of a problem.
I have many different types of game elements. These are all of type Entity.
There are many types of Entities, including ones that are visible and need to be drawn on the screen. These entities are of type VisibleEntity which extends Entity.
Like this, I have many different hierarchical types for the elements in the game.
My question is this:
What data structure has the best run-time complexity when issuing the following types of queries?
1) get objects of type Entity
2) get objects of type VisibleEntity
3) get objects of type SomeSpecificGameObject
The trivial solution is to store them all in a list, and iterate through them all, and if they are of the type specified, add them to a list that is to be returned.
Obviously, it is not feasible when computation is done at every frame for certain elements in the screen.
What is the best way to keep track of all this?
I appreciate any response!
The other trivial solution is to maintain one list per type. Store each list in a hashmap, with the type as the key. It’s about as instant as you can get, and will only cost you one pointer per item. It also makes it possible to add the same object to more than one list. That will handle your hierarchy.
If you want to reduce the space required by the approach above, have each list-of-entities object also store pointers to the lists of its subclasses. That way, a VisibleEntity would live only in the VisibleEntity list, and not in the lists for its subclasses. To find all VisibleEntities, you do a hash lookup for the the main list, and then do a recursive search through the children for the subclasses. This is a simple tree structure.
Depending on the height of your tree and the number of objects, you might be better off with the first approach. It’s a complexity vs time vs space tradeoff.