Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Continuously spawn enemies with a delay  (Read 3126 times)

0 Members and 1 Guest are viewing this topic.

mikewu63

  • Newbie
  • *
  • Posts: 1
    • View Profile
    • Email
Continuously spawn enemies with a delay
« 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


eXpl0it3r

  • SFML Team
  • Hero Member
  • *****
  • Posts: 11032
    • View Profile
    • development blog
    • Email
Continuously spawn enemies with a delay
« Reply #1 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.
Official FAQ: https://www.sfml-dev.org/faq.php
Official Discord Server: https://discord.gg/nr4X7Fh
——————————————————————
Dev Blog: https://duerrenberger.dev/blog/