I'm designing a simple game, which uses Java 2D and Newtonian physics. Currently my main "game loop" looks something like:
do {
for (GameEntity entity : entities) {
entity.update(gameContext);
}
for (Drawable drawable : drawables) {
drawable.draw(graphics2d);
}
} while (gameRunning);
When an entity is instructed to update itself it will adjust its velocity and position based on the current forces applied to it. However, I need entities to exhibit other behaviour; e.g. if a "bad guy" is shot by a player the entity should be destroyed and removed from the game world.
My question: What is the best way to achieve this in an object oriented manner? All examples I've seen so far incorporate the game loop into a God class called something like Game
, which performs the steps: detect collisions, check-if-bad-guy-killed, check-if-player-killed, repaint, etc and encapsulates all the game state (lives remaining, etc). In other words, it's very procedural and all the logic is in the Game class. Can anyone recommend a better approach?
Here are the options I've thought of so far:
- Pass a
GameContext
to each entity from which the entity can remove itself if required or update the game state (e.g. to "not running" if the player is killed). - Register each
GameEntity
as a listener to the centralGame
class and take an event oriented approach; e.g. a collision would result in aCollisionEvent
being fired to the two participants in the collision.