1
\$\begingroup\$

I am building a simple 2D game with SFML and have a GameState object that contains a Plane and a vector of Enemies. THe plane is represented by a triangle and the enemies by a rectangle. The plane object has bullets and I am wondering what is the most appropriate way of handling collision between the bullets and the enemies. The structure of the code is the following :

 GameState
    /\
   /  \
Plane Enemies
  /
Bullets

Every object has Render and Update and possibly HandleInput methods. The way I think that this could work is if I pass the enemies vector to the plane's update method which in turn calls the bullets update method and there I do the check. Is this ok ? Is there an easier and more solid method of doing it ?

\$\endgroup\$
0
\$\begingroup\$

If you're making a basic game, passing in the vector of bullets to the enemies isn't a huge problem. Is it particularly nice? I don't think so. This is the kind of issue that will scale with the complexity of the game.

Using the KISS approach, I think the best way you could solve this would be to implement a collide() method in which the actor/entity/gameobject can test its collision against another actor/entity/gameobject. Using this, you could iterate over them inside of your GameStates update(). Something like...

    // for every enemy, test against every bullet..
    for(auto enemy : _enemies) {
        for(auto bullet : _bullets) {
            if(enemy->collides(bullet)) { 
                // handle behaviour..
            }
        }
    }

In terms of performance, this will scale badly depending on how many enemies and bullets you have.. but at least the logic will be in the GameState (where it should be), and not inside of an entity.

This approach is not wonderful practice, but it'll work. If you'd like to look into more complex collision systems then have a look into Box2D, or try making one yourself using quadtrees/spatial partitioning. The latter is, of course, more complicated.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ awesome, i will look into those :) \$\endgroup\$ – Martin Spasov Nov 19 '17 at 9:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.