SFML community forums

Help => General => Topic started by: mikewu63 on April 02, 2017, 02:56:56 pm

Title: Continuously spawn enemies with a delay
Post by: mikewu63 on April 02, 2017, 02:56:56 pm
Hello,

I've recently started to learn SFML, and I'm currently working on a 2D game. I already have a player class and a bullet class, but now I'm having problems with spawning the enemies. Basically my idea is to spawn enemies (objects from class Enemy) with a delay of 3000ms. These enemies will spawn at a random position 0 to 600 for X and Y. However with my current code I can only spawn a single enemy object and draw it in the while loop.

This is my current code for the enemy class:

    class Enemy {
public:
   Enemy(sf::Vector2f size) {
      en.setSize(size);
      en.setFillColor(sf::Color::Red);

   }
//... move();
   void setPos(sf::Vector2f pos){
      en.setPosition(pos);
   }
   void drawTo(sf::RenderWindow &win) {
      win.draw(en);
   }
//... randomPos() and randomPos2() are here

private:
   sf::RectangleShape en;

};

And my code to create a new enemy object:

        Enemy newEnemyObject({ 20, 20 });
   newEnemyObject.setPos({ newEnemyObject.randomPos(), newEnemyObject.randomPos2() });


I obviously can't put it in a function and put it delay on it and set it in the main loop because that will stop the whole program. I thought about threading, but how will I draw it?


Any help would be appreciated

Title: Continuously spawn enemies with a delay
Post by: eXpl0it3r on April 02, 2017, 07:43:12 pm
Use an sf::Clock and check the elapsed time. If it's larger than 3s, add a new sprite to the std::vector and restart the clock.