Sunday, November 26, 2017

c++ - Identifying Entity 'Types' in an Entity-Component System


If an Entity has no explicit 'type' (e.g. player) and is simply a collection of components, how do I identify the entities that my systems should and should not be working on? For example, in a game of Pong the paddle and ball both collide with the window boundaries. However, the collision handling systems for each will be different, therefore a system should not handle entities of the wrong type.


void PlayerCollisionSystem::update(std::vector entities) {
typedef std::vector::iterator EIter;
for (EIter i = entities.begin(); i != entities.end(); ++i) {

Entity *player = *i; // How do I verify that the entity is a player?

// Get relevant components.
PositionComponent *position = player->getComponent();
VelocityComponent *velocity = player->getComponent();
SpriteComponent *sprite = player->getComponent();

// Detect and handle player collisions using the components.
}
}


Both the player and the ball share the same relevant component types for collision handling yet their system implementations will be different.


If I have a container of all game entities, how do I identify specific types of entity without inheriting Entity or including a member variable such as std::string type, in which case an entity is no longer simply a collection of components?



Answer



Nicol Bolas' answer is straight on, but stepping aside and looking at your problem from a distance: you really don't need the type of the entity.


You only need to care whether "does the object have component X" or not and your problem is that you have not properly identified X. If two objects behave differently then give them different components or just put a boolean flag on the component if it to make it behave differently for different object configurations. Use the component system to make decisions about behavior, not the entity "type." That's the whole point of using components.


You are completely allowed to have a PaddlePhysics component/system and a separate BallPhysics component/system if they behave differently. Or you can break down the components into more granular pieces such that you have a Bounce component that only the Ball has and a StopAtBoundary component that both Ball and Paddle have if part of the behavior is complicated enough to justify sharing the code. Or you can just make a PongPhysics component that has a boolean flag Bounces set true for the Ball and false for the Paddle. You could even make a base WallCollision component and then derive that component to get a BallWallCollision that adds the extra behavior needed there.


No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...