Hello,I'm trying to create a simple Shoot 'em Up game in SFML,and I created an entity class called "enemy" currently containing two members,a texture and a shape:
class enemy {
public:
sf::Texture t;
sf::RectangleShape s;
};
I created two objects from this class,one called "basic_enemy",and the other a vector called "enemies":
enemy basic_enemy;
std::vector<enemy> enemies;
I then wrote a function that randomly chooses between two sets of parameters to assign to the "basic_enemy" object,effectively choosing what type of enemy it will be (So far there are only two):
void enemy_spawner() {
std::string texture_path;
sf::Vector2f enemy_size;
sf::Vector2f enemy_origin;
switch (int r1 = rand() % 2) {
case 0:
texture_path = "res/images/enemy1.png";
enemy_size.x = 70;
enemy_size.y = 70;
enemy_origin.x = 35;
enemy_origin.y = 35; break;
case 1:
texture_path = "res/images/enemy2.png";
enemy_size.x = 100;
enemy_size.y = 100;
enemy_origin.x = 50;
enemy_origin.y = 50; break;
}
basic_enemy.t.loadFromFile(texture_path);
basic_enemy.s.setSize(enemy_size);
basic_enemy.s.setOrigin(enemy_origin);
basic_enemy.s.setTexture(&basic_enemy.t);
int spawn = rand() % 640 + enemy_origin.y;
basic_enemy.s.setPosition(sf::Vector2f(spawn, -(enemy_origin.y)));
}
(I'm aware the name "enemy_spawner" is not an accurate description so I'll change it later)
Then I tried to set it up so that a new enemy type is chosen every two seconds,assigned to the "basic_enemy" object which will have it's content copied to the new element added to the "enemies" vector:
sf::Time elapsed_time;
sf::Clock clock;
while (w.isOpen()) {
sf::Event e;
while (w.pollEvent(e)) {
}
sf::Time delta_time = clock.restart();
elapsed_time += delta_time;
if (elapsed_time > sf::seconds(2)) {
for (int i = 0; i < 1; i++) {
enemy_spawner();
enemies.push_back(basic_enemy);
elapsed_time = clock.restart();
ii++;
}
}
...
}
The issue here is that for some reason,everytime a new enemy type is chosen,the texture corresponding to that enemy is then re-assigned to all other existing enemies...
Here's an example of an enemy of the second type(with the "enemy2.png" texture):
And here's the same enemy roughly two seconds later,after an enemy of the first type(with the "enemy1.png" texture) was spawned:
At first I thought all of the elements of the vector were being rewritten every two seconds,but now I'm fairly certain that's not the case,because every enemy retains it's the size and x coordinates initially assigned to it for example,but still change textures for some reason...
Any idea what's causing this?