Hello SFML community,
I'm using SFML 2.1 with xcode 5 on my macbook air and I am somewhat new to SFML & C++(I have a couple of months under my belt). I am in need of some help when it comes to Sprites & memory management (EXAMPLE: removing bullets when they go off screen, etc). I am creating a platform game and I have been stuck for weeks trying to figure this out. I have looked on a good amount of forums regarding this issue and I've come across examples where erase(it) being used inside of a for loop using an iterator. I've tried this but it does not work for me.
I would like to know how to clear out a vector that contains Sprites (or class objects w/ Sprites) using an iterator. And I would like these Sprites to be cleared out based on a boolean value. Which ever way I try to implement this I get an BAD_ACCESS error or the program crashes after the Sprite or object is removed from the vector using erase(). I have tried ever way I can think of but nothing works.
Instead of posting my game which contains hundreds of lines of code I wrote a simpler code, please examine it and help me understand what I am doing wrong.
#include <SFML/Graphics.hpp>
//#include "ResourcePath.hpp"
#include <iostream>
#include <vector>
int main()
{
bool is_Alive;
is_Alive = true;
sf::Sprite* Sprite;
Sprite = new sf::Sprite;
std::vector<sf::Sprite> SpriteVector;
typedef std::vector<sf::Sprite>::iterator iter;
//loading projectile image
sf::Texture* projectileImage;
projectileImage = new sf::Texture;
projectileImage->loadFromFile("fireball.png");
Sprite->setTexture(*projectileImage);
//Creating game window
sf::RenderWindow window(sf::VideoMode(800, 600), "SFML Game");
//set famerate to 60 FPS
window.setFramerateLimit(60);
window.setKeyRepeatEnabled(false);
sf::Event event;
float moveSpeed = 0;
//variable that keeps game loop running
bool play = true;
//Game Loop
while (play == true)
{
//Events
while (window.pollEvent(event))
{
if (event.type == sf::Event::KeyPressed && event.key.code == sf::Keyboard::Space)
{
SpriteVector.push_back(*Sprite);
}
if (event.type == sf::Event::Closed)
{
}
}
//LOGIC-----------------------------------------------------------------------------------------------------
std::cout << "SpriteVector is..." << SpriteVector.size() << "\n";
for (iter it = SpriteVector.begin(); it != SpriteVector.end(); it++)
{
if ((it)->getPosition().y <= 600)
{
(it)->move(5, 5);
}
}
//RENDERING
window.clear();
for (iter it = SpriteVector.begin(); it != SpriteVector.end(); it++)
{
if ((it)->getPosition().y <= 600)
{
window.draw(*it);
}
if ((it)->getPosition().y >= 601)
{
SpriteVector.erase(it);
std::cout << "Erasing..." << (&it) << "Container size..." << SpriteVector.size() << "\n";
}
}
window.display();
}
//Clean Up
window.close();
return 0;
}