Advertisement

Creating Enemies From a Class

Started by March 30, 2021 08:50 AM
4 comments, last by yusufabi 3 years, 7 months ago

Hi. I have an enemy class like this:

//enemy class
class enemy {

public:
sf::RectangleShape rect;
float bottom, left, right, top;
sf::Texture enemytexture;
sf::Sprite enemysprite;
enemy(sf::Vector2f position, sf::Vector2f size, sf::Color color) {
enemytexture.loadFromFile("dwarf.png");
enemysprite.setTexture(enemytexture);
}

void update() {
fireanis.setPosition(rect.getPosition().x - 9, rect.getPosition().y - 45);
fireanis.setScale(0.5, 0.5);

}
};

int main () {.......

//create

enemy e1(enemy(sf::Vector2f(1900, 910), sf::Vector2f(15, 10), sf::Color(255, 255, 255, 0)));

//update

e1.update();

//draw

window.draw(e1.enemysprite);

/////////////////////////////////////////////////////////////////////////////////////////////

if i would like to create a new enemy i m using same way like enemy e2,e3,e4…..

But it doestn seem effective way for game programming i think.

My question is how can i create and draw multiple enemies with loops or are there another ways? is there any sample code?

The simplest way is that you create an array of enemies and then you can loop over them.

https://www.cplusplus.com/doc/tutorial/arrays/

Advertisement

Vectors might be a more better, more forgiving fit if you want to add and remove enemies dynamically:

Unfortunately I haven't been able to find a tutorial as nice as the one provided by @kylotan .
Not on the go-to Cpp sites isocpp.org, cplusplus.com and en.cppreference.com, anyways.

The closest I got was this: https://en.cppreference.com/book/intro/vector,​ but it's probably best to dive right into the
reference material instead: https://www.cplusplus.com/reference/vector/vector/vector/

Kylotan said:

The simplest way is that you create an array of enemies and then you can loop over them.

https://www.cplusplus.com/doc/tutorial/arrays/

Thank you for your answer

SuperVGA said:

Vectors might be a more better, more forgiving fit if you want to add and remove enemies dynamically:

Unfortunately I haven't been able to find a tutorial as nice as the one provided by @kylotan .
Not on the go-to Cpp sites isocpp.org, cplusplus.com and en.cppreference.com, anyways.

The closest I got was this: https://en.cppreference.com/book/intro/vector,​ but it's probably best to dive right into the
reference material instead: https://www.cplusplus.com/reference/vector/vector/vector/

Thanks for your advice and shared links. I have to search vectors. Best regards.

This topic is closed to new replies.

Advertisement