Bullet attacking an Enemy

Hi everyone. So I'm working on a Tower Defense game. If you're not familiar with Tower Defense, all that is necessary for you to know for this post is that Enemies move through a path while the user constructs Towers that periodically shoot some kind of projectile that inflicts damage on the Enemy.

Here's my trouble. I'm trying to design my Bullet class and I can't quite decide what I should do. The designer tells me that he wants bullets from towers to "follow" an enemy until they collide. He also says that if a bullet is following an enemy and the enemy dies before the bullet reaches the enemy, then the bullet should just disappear.

So I'm trying to decide how I can accomplish this. The "following" mechanism isn't too bad... I just do something like bullet.moveHoriz((target.x - bullet.x)*bullet.vel). At least something similar to that. The difficulty lies with how I should tell the bullet when its enemy has been defeated. I was thinking about having the Bullet store an Enemy pointer, but then how does the bullet know when there's no longer a proper Enemy to follow?

One possible solution I thought of was to have each Enemy have a std::vector of Bullet pointers which contains every bullet that is "following" the Enemy. Then, in the enemy destructor I could do something like
1
2
for (int i=0; i < followers.size(); i++)
  followers[i]->die();


Does that seem like a valid solution?.. Or is there a better way you can think of?

Thanks.
What happens to the enemy when it dies?
You can make your bullet checking for its target health before moving, if the enemy is still alive the bullet moves, otherwise it disappears
Well the enemy "dies" or gets deleted when its hp reaches zero. So the trouble is the Bullet only has a pointer to the enemy and once that enemy goes out of scope the Bullet's pointer doesn't point to anything... but it's not like it automatically becomes NULL instead so I couldn't check for that. I don't think it's a good idea to try to check the health of the enemy pointed to by the pointer from the bullet because that pointer could be invalid at that point. I hope that makes sense...
Can you keep the enemy object a bit after it died so the bullet can check if it is alive?
An other solution would be having a member container in the enemy class.
I would suggest you a std::deque or a std::list instead of a vector as you can insert and remove elements more efficiently.
you're right a std::deque would be more appropriate in this case. I COULD keep the enemy around a little longer than when it's killed but I don't want MORE towers to fire bullets at an enemy that was supposed to have died. I think I'll just go with the solution I had in the first post but using a deque instead.
Topic archived. No new replies allowed.