Jump to content
  • Advertisement
Sign in to follow this  

Looking for a more automatic way for objects to call functions

This topic is 3941 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

I have a list of missiles, mis1 to mis 20, and I'm tired of coding missile1.whatever = annother_whatever missile2.whatever = annother_whatever ... missile20.whatever = annother_whatever Is there a way to put this into a few lines? Is it even a good way? When the missiles die, missileactive = false; and it is not drawn until it is needed. I am looking for a better way to do this too. :) And finally, I would like to know what this is called, so that I may tell all my friends. Thank you!

Share this post

Link to post
Share on other sites
Create a vector which contains the active missiles.
#include <vector>
typedef std::vector<Missile> Missiles;
Missiles missiles;

When a new missile is created, add it to the vector:
Missile added(constructor_args);

This will have the vector store a copy of the missile. To perform a given operation on all missiles, define a function which performs that operation and apply it to the entire vector:
#include <algorithm>
void update(Missile &m) { m.whatever = another_whatever; }
std::for_each(missiles.begin(), missiles.end(), &update);

To detect which missiles are dead and remove them from the vector, define an is-dead function and use remove-if:

bool is_dead(const Missile &m) { return ! m.active; }
missiles.erase( std::remove_if( missiles.begin(), missiles.end(), &is_dead ),
missiles.end() );

This moves all dead missiles to the end of the vector and then removes them in one sweep, thus guaranteeing that only live missiles are in the vector.

Share this post

Link to post
Share on other sites
Man, I've never looked into the STL algorithm include, std::for_each, std::remove_if, good stuff!

Always, always learning new things about C++ :)

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement

Important Information

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

GameDev.net is your game development community. Create an account for your GameDev Portfolio and participate in the largest developer community in the games industry.

Sign me up!