Jump to content
  • Advertisement

Archived

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

zaphod

Catch-22

This topic is 6649 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
Advertisement
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,
Eck
eck@home.com

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.

Participate in the game development conversation and more when you create an account on GameDev.net!

Sign me up!