The title might be a tad simple for the purpose, but bear with me.

I'm a tad lost about how to do the interaction between game objects. I use an entity-component-system framework and I've got the basics up and running: the player can run around, collisions get reported correctly, graphics are updating nicely and so on. I even have an AI enemy wandering around.

However, what if I want to hit the enemy with a sword? How do I know what the player hit? The naive solutions (for e.g. Box2D) do something like this:

void BeginContact(b2Contact* contact)
    // Get the colliding bodies
    b2Body* body1 = contact->GetFixtureA()->GetBody();
    b2Body* body2 = contact->GetFixtureB()->GetBody();

    // Get the user data
    int body1UserData = body1->GetUserData();
    int body2UserData = body2->GetUserData();

    // Check if the enemy hit the player
    if((body1UserData == PLAYER && body2UserData == ENEMY) ||
       (body2UserData == PLAYER && body1UserData == ENEMY))
        // Enemy collided with player, damage the player

This solution "works", but to my understanding has very little use in real-life scenario. Again: what if I want to hit an enemy with a sword? Which enemy did I hit? Should I really keep adding and removing the sword collider from the game world? I can't really find any good reads on this topic. There's lots of articles and books about game engines, but the actual game architecture is commonly left out.

I'm purposefully leaving this a bit vague since there is probably multiple ways to do that. I'm after some real-life usage examples and how to do things in a bigger scale, where there's tens of different enemies / entities, various weapons and so on.


2 Answers 2


You need to send events around. When the you have a contact, emit an event of type "contact" with data "entity1" and "entity2".

Now your system that resolves the attacks listens to events of type "contact". Therefore, it can check if one of the entities was attacking, and if yes, using what weapon.

Well, you can go on from there, depending on your entities/components/systems and supported interactions.

  • \$\begingroup\$ If there's no contact (e.g. player does not touch enemy but swings a sword), how do we know which enemy we should hit? \$\endgroup\$
    – manabreak
    Nov 18, 2014 at 15:28
  • \$\begingroup\$ well, shouldn't you then have a contact with the sword and the enemy? Or, if the sword is not treated separately, use a bigger bounding volume for the player that encompasses the sword as well \$\endgroup\$
    – Babis
    Nov 18, 2014 at 15:51

What I have done in previous projects is send all Entity class members to a central event hub and send a boolean variable telling whether contact has been made or not. the Entity itself then determines what to do by the provided information


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .