Hey Guys,

I'm building an asteroids-like game and I'm needing to be able to apply the same operation too all of the different "aliens" on the screen. When I had two aliens on the screen I performed all of the functions manually but that is bad program design. I created a vector and all of the sudden my aliens stopped performing the functions that were called when I looped through the vector.

Here's the working code:


Here's the bad code:

  std::vector<Alien> aliens;
  Alien alien1;
  Alien alien2(100,200,30,30,1,172);

  //game loop has started

  for(int i = 0; i< size; i++)

  //game loops

I created a static array just to see if it was a vector problem and alas I cannot get it to work with a static array either. I'm thinking that I may be needing to setup some sort of copy constructor that isn't currently setup or maybe I'm creating the vector or array incorrectly. Is the solution to this problem simple?


Recommended Answers

All 3 Replies

Could you post your alien class?

Thanks Nate, but I managed to get it fixed myself after doing a little reading and I think it had to do with how I'm forming my vector. The code that worked is:

  std::vector<Alien*> aliens;
  Alien alien1;
  Alien alien2(100,200,30,30,1,172);

  // game loop begins

  for(int i=0;i < aliens.size();i++)

  //game loops

If you want to you can create aliens using the new operator and store them directly into the vector instead of creating aliens individually then storing the reference of them into this vector of pointers.

std::vector<Alien*> aliens;

aliens.push_back(new Alien());
aliens.push_back(new Alien(100, 200, 30, 30, 1, 172));

You just have to remember to call delete on each element and set it to 0 if you plan on removing/clearing an element (or you can put your vector of aliens in an object like a map or level that manages this for you).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, learning, and sharing knowledge.