Hey everyone.
My program crashes because of the these 3 lines of code.
1. (*it)->createBullet(bulletTexture,bulletImage,shipImage);/// creates a bullet of a specific object
2. (*it)->moveBullet(bulletImage); ///move the bullet of a specific object
3. (*it)->drawBullet(myGameGUI,bulletImage);///draws the bullet of a specific object
i am using vector to store objects of class and iterating over the vector to use the objects to call specific functions from the class.
What is the problem? why does it keep crashing?
Here is the main function
int main()
{
int i=0;
Ship shipObject;
Bullet bulletObject;
vector <Bullet*> bulletArsenal;
vector<Bullet*>::iterator it = bulletArsenal.begin();
myGameGUI.create(sf::VideoMode(1000,680), "WorkingGameProject");///Creates the Window
sf::Style::Default;
Background();///Creates the background
shipObject.createShip(shipTexture, shipImage);///calls function ship class and creates the ship
while(myGameGUI.isOpen())
{
while(myGameGUI.pollEvent(action))
{
closeFunction();
}
bool fire =false;
shipObject.moveShip(action, shipImage,myGameGUI);///Calls function from ship class and Moves the ship
if(sf::Keyboard::isKeyPressed(sf::Keyboard::Space)){
bulletArsenal.push_back(&bulletObject);/// adds a new object to the vector
(*it)->createBullet(bulletTexture,bulletImage,shipImage);/// creates a bullet of a specific object *********
fire=true;
}
(*it)->moveBullet(bulletImage); ///move the bullet of a specific object***********************
myGameGUI.clear();///clears screen
myGameGUI.draw(backgroundImage);///draws the background
shipObject.drawShip(myGameGUI,shipImage);///draws the ship
(*it)->drawBullet(myGameGUI,bulletImage);///draws the bullet of a specific object **************
myGameGUI.display();
if(fire==true)
++it;
}
return 0;
}
You just keep incrementing 'it'. It will eventually pass the end() iterator and refer to memory outside the vector.
You probably want to do something along the lines of the following to draw all the bullets:
for (auto &bullet : bulletArsenal) {
bullet->drawBullet(...);
}
Hello!
When you call (*it)->createBullet(bulletTexture,bulletImage,shipImage);
it does not appear as though there are any elements in the array, and (*it)
is null which is why the program might be crashing.
Let me know :-)
- TFB