简体   繁体   中英

How do I spawn more enemies? SDL2/C++

I am learning SDL and I want enemies to spawn randomly after some time interval. I know how to make 1 enemy render to the screen, but I'm struggling rendering more than 1. In my program I have an enemy class, which has functions that draws, checks collision, renders and moves the enemy. Can you give me some code examples, I would prefer SDL/C++.

Probably not going to get any examples given but I would recommend one simple concept: separate movement from rendering. Also another, build lists of enemies.

You have an enemy class, which is good. Now manage a list of them. When you want to add a new enemy, create a new object and add it to your list.

Then in two steps, loop through your entire list - moving all the enemies (meaning changing the X,Y, etc in the object but not drawing).

Then go through the list again and render the enemies.

It becomes a simple case of managing a list of objects, and object life times (removing from list when enemy is dead, etc).

I suggest placing your enemies into a std::vector or std::queue . Each enemy should have it's own coordinates (for easy placement).

In your update or refresh loop, iterator over the enemy list, processing them as necessary.

In another timing loop or thread, you can add enemies to the container. This should not affect the code of the rest of the program; except that there may be more data (enemies) in the vector to process.

Example:

class Enemy_Base
{
  public:  
    virtual void draw(/* drawing surface */);
};

class Troll : public Enemy
{
  //...
};

std::vector<Enemy_Base *> enemy_container;

//...
std::vector<Enemy_Base *>::iterator enemy_iter;

// Rendering loop
for (enemy_iter = enemy_container.begin();
     enemy_iter != enemy_container.end();
     ++enemy_iter)
{
  (*enemy_iter)->draw(/*..*/);
}

// Create a new enemy
Troll * p_troll = new Troll;
enemy_container.push_back(p_troll);

This example is to demonstrate concepts. The real implementation should use smart pointers, and factory design pattern.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM