In my 2D game I have a PhysicsEngine
class. It currently does two things:
- Called every frame to apply global forces on all entities (e.g. gravity).
- Called by the
CollisionDetector
to do the physics part of collision response.
Currently, (almost) all physics-related logic goes through this class (including single-line things like entity.applyImpulse(..)
).
My question is, from an OO design perspective: is it okay for an entity to do simple physics logic by itself, or should all physics logic (even simple things) go through classes dedicated to it?
For example: in my game, when spotting a collision the CollisionDetector
notifies both entities to take care of gameplay related logic, and the PhysicsEngine
to take care of physics related logic. Looks like this:
// on collision between entityA and entityB
entityA.handleCollision(entityB); // take care of gameplay
entityB.handleCollision(entityA); // take care of gameplay
physicsEngine.handleCollision(entityA, entityB); // take care of physics
But what if, for example when a Missile
hits something I want to apply an impulse on the hit object? (In addition to the physics that always happens on collisions, in PhysicsEngine
).
This is easy to do by simply adding about 3 lines of code to the handleCollision()
method in Missile
:
public void handleCollision(Entity entity) {
Vector impulse = entity.getPosition().subtract(this.position);
impulse.scaleBy(5);
entity.applyImpulse(impulse);
explode();
}
However, this would be putting physics logic in a 'gameplay' class. Should the Missile
delegate to the PhysicsEngine
in some way? Or is it okay that it would contain physics logic?
Another example I encountered in my game, is that when an entity 'fires' a Missile
, I want to apply an impulse on the entity to push it backwards. Again, this can be done easily by adding 2-3 lines to the fire()
method in the Entity
subclass, but I'm not sure it's okay design-wise to mix gameplay and physics logic.
So, is it acceptable to have simple physics logic mixed with the gameplay logic? Or should I always separate the two?
How is this done in 'serious' games?