1
\$\begingroup\$

I have a problem with the handling of explosions in my game.

Currently, I have an entity create an explosion when it is destroyed (in the destructor). The issue with this is that when I change states, all my game objects are deleted. This causes explodable objects to create explosions when my EntityManager is already deleted.

I'm still pretty new to game development and I believe my design is very poor. How can I solve this problem?

\$\endgroup\$
2
  • \$\begingroup\$ Polling for how others solve a problem is too broad for this site (see the help center), but your concrete problem is good so I refocused the question only on that. \$\endgroup\$
    – user1430
    Oct 21, 2014 at 23:52
  • 1
    \$\begingroup\$ By the way, it's odd that by the time your entities are being deleted the entity manager is already deleted. In general you should make sure that objects are deleted inside-out, so anything that is "managed" should be deleted before, or as the very first step of, the "manager" object's deletion (or at least the tie between those objects should be severed). \$\endgroup\$
    – user1430
    Oct 21, 2014 at 23:58

1 Answer 1

4
\$\begingroup\$

Constructors and destructors in C++ are about the lifetime of the object. Your problem is that you are mixing up the lifetime with the desired behavior of the object.

The solution is to decouple them.

Give the appropriate entities an "OnDestroy" function, which is called by your game logic when the entity should be (according to the rules of the game) destroyed.

Leave your destructor to do what it should do: anything necessary when (according to the rules of the language) the object itself should be excised from your program's memory.

Then you create your explosions in OnDestroyed. When you transition between game scenes, that causes the entities to be deleted, cleaning up and invoking the destructor, but it doesn't need to call the OnDestroyed method, so no new entities will be created.

\$\endgroup\$
1
  • \$\begingroup\$ Hey, thanks for the explanation. I will try to separate the logic with the lifetime. This is my first attempt at a mildly complex game, things are becoming exceedingly complex as the code base grows. \$\endgroup\$
    – brandonto
    Oct 22, 2014 at 0:21

You must log in to answer this question.

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