Jump to content
  • Advertisement


This topic is now archived and is closed to further replies.



This topic is 6819 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

Ok heres my problem: I''m programming a simple 2d space shooter in c++ (no surprises there then) I''ve got a ''player'' class and an ''enemy'' class. For the purposes of collision detection they both need to refer to each other, so, say, the player.missiles.run(enemy* e) method needs a pointer to an enemy which it uses to detect a collision with that enemy and affect the enemy accordingly. Also the enemy.missiles[i].run(player* p) function takes a pointer to a player for the same reason. Uh-oh, catch-22, to define the player class I need to have defined the enemy class and to define the enemy class I need to have defined the player class! At the moment I have solved this problem by creating a third class ''collision_detect(player* p, enemy* e)'' which is defined after the player and enemy classes, but this seems like ugly code. For example, the player.run() method calls a method cannon.run() which calls a method missile.run() for an array of missiles. Rather than having the code for detecting and acting on a collision between a misile and a given enemy *here*, it resides in a different class entirely (collision_detect). This seems against the idea of OOP. Any ideas, or am I just being fussy? Thanks a lot Felix.

Share this post

Link to post
Share on other sites
What you need to do is forward declare each class in the header for the other.

In player.h:

class enemy;

class player {
void run( enemy* );

And the opposite in enemy.h.

You then need to include player.h in enemy.cpp (and vice versa).

Share this post

Link to post
Share on other sites
LordFoul''s solution is correct for solving circular dependancies. We''ve all ran into this problem before. However, I think you might be able to solve this problem a different way. Make a virtual base class called ScreenObject that has a method for detecting colisions that takes a ScreenObject pointer. Then have the player and enemy classes inherit from ScreenObject. This might be what you are looking for since it allows you to do some other cool stuff.
Let me know if this works for you,

Share this post

Link to post
Share on other sites

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!