Hello all. Sorry for spamming the forum with beginner questions lately, this one will be the last for a while, I promise.
I'm experimenting with a tile engine. I have two different methods to set a specific tile, one uses arrays, one uses vectors.
First, here's the one with arrays:
void Tileset::setTile(int tileNum)
{
tileRect = new sf::IntRect[numTiles];
int counter = 0;
for(int texture_h = 0; texture_h < numTilesY; texture_h++)
{
for(int texture_w = 0; texture_w < numTilesX; texture_w++)
{
if(counter < numTiles)
{
tileRect[counter].left = texture_w * tileWidth;
tileRect[counter].top = texture_h * tileHeight;
tileRect[counter].width = tileWidth;
tileRect[counter].height = tileHeight;
counter++;
}
}
}
this->setTextureRect(tileRect[tileNum]);
delete tileRect;
}
In the header, tileRect is defined like this:
sf::IntRect *tileRect;
Now, here is the one that uses vectors:
void Tileset::setTile(int tileNum)
{
for(int h = 0; h < numTilesY; h++)
{
for(int w = 0; w < numTilesX; w++)
{
rect.left = w * tileWidth;
rect.top = h * tileHeight;
rect.width = tileWidth;
rect.height = tileHeight;
subRect.push_back(rect);
}
}
this->setTextureRect(subRect[tileNum]);
subRect.clear();
}
In the header, rect and subRect are defined like this:
std::vector <sf::Rect<int>> subRect;
sf::Rect <int> rect;
Both of these are working fine, and this is what I don't understand. In both methods, I have to destroy the temporary rectangles (tileRect and subRect) after they have been assigned to the texture, othervise they will produce memory leaks (the vector-based one is quite dangerous, it keeps allocating more and more memory until the app is closed).
But how can SFML display the area defined by the rectangle, if the rectangle doesn't even exist any more? Once a set of coordinates are assigned to the setTextureRect function, it will store them until they have been overwritten by another set, or the app is closed? Is this code the way it supposed to be done, anyway, or just plain broken and dangerous?
Thanks for your help in advance.