Search code examples
c++sfml

My renderwndow becomes blank and stops working


Actually i was trying to make a bullet shooting code.I used vectors and added the sprite into it and the positions in seperate vectors.But when i run my program my window stops working.Here is the code.I hope its not repeated.

#include <SFML/Graphics.hpp>
#include <iostream>
#import "bulletcode.h";
#include <vector>
using namespace std;
using namespace sf;
int main()
{
vector<Sprite> bullets;
vector<float> xp;
vector<float> yp;
sf::RenderWindow window(sf::VideoMode(900, 600), "SFML works!");
sf::CircleShape shape(75.f);
shape.setFillColor(sf::Color::Green);
Texture bullet;
bullet.loadFromFile("bullet.png");
shape.setPosition(400,100);
while (window.isOpen())
{
    sf::Event event;
    while (window.pollEvent(event))
    {
        if (event.type == sf::Event::Closed)
            window.close();
    }
    if(Keyboard::isKeyPressed(Keyboard::Space)){
        Sprite bulletsp;
        bulletsp.setTexture(bullet);
        bulletsp.setScale(0.8,0.8);
        bullets.push_back(bulletsp);
        xp.push_back(shape.getPosition().x);
        yp.push_back(shape.getPosition().y);
    }
      for(int i=0;i<=bullets.size()-1;i=i){
        yp[i]=yp[i]+0.2;
        i++;
        bullets[i].setPosition(xp[i],yp[i]);
        window.draw(bullets[i]);
     }

    window.clear();
    window.draw(shape);
    window.display();
}

return 0;
}

Solution

  • You're incrementing i in the loop. So on the last iteration, you'll be accessing beyond the ends of the arrays.

    You probably want to replace the i=i in the loop declaration with i++, and not increment i in the loop body.