I have been working to create a game in C++. A World
class contains all game-state related objects and the main game loop function.
class World {
Clock clock;
Map map;
std::vector<Entity*> entities;
...
All entities in my game inherit from the abstract class Entity
. For example:
class Player: public Entity {...};
class Enemy: public Entity {...};
class Bullet: public Entity {...};
Entities are updated each frame by iterating through a list of all entities and calling the update()
method on each one.
To account for varying frame rates, I pass the elapsed time in each frame as a float delta
to the update method (like most other game engines). The problem I run into is all the different things an entity might need to reference in update()
.
The Entity
class defines the virtual update method as follows:
virtual void update(float delta) = 0;
Calling this function from the game loop looks like this:
for(int i = 0; i < entities.size(); i++) {
entities[i]->update(clock.get_delta());
}
This works great. But now, let's say for example that we want to add a feature where Player
can move faster on different surfaces. To know what surface the player is on would require access to the Map
object belonging to the World
class.
We could add that to the virtual update method:
virtual void update(float delta, Map *map) = 0;
But now Enemy
and Bullet
's update functions have to take the new map parameter even though they don't use it.
The same would go for any other object or variable an entity needs in its update method. Before long, there would be dozens of parameters (game map, list of other entities, game state information) cluttering the method definition.
My question is: How can I prevent this? I tried passing a reference to World
as the only argument, but it resulted in circular dependencies.
I solved this in my game by storing a Map*
in the Player
class. Works great if you never have to change it.