Hellow!
I'm using SFML 2.4.2 with Code Blocks for some weeks. I've herd that RenderTexture is quite a useful thing so I tryed to use it.
When I use it in the main function then it works properly, but when i try to write the same comands in another function or class method it doesn't work correctly. I paste two pices of code that must give the same output (because the comands are almost the same) but they don't. If someone knows how to fix it or what mistake have I made, write please.
Code that works properly
#include <SFML/Graphics.hpp>
using namespace sf;
int main()
{
//Block of the same functions
Sprite sprite1;
RenderTexture rendertexture;
rendertexture.create(32, 32);
Image im1;
im1.create(32, 32, Color::Red);
Texture tex1;
tex1.loadFromImage(im1);
sprite1.setTexture(tex1);
sprite1.setPosition(0, 0);
rendertexture.draw(sprite1);
//Block of the same functions/
RenderWindow app(VideoMode(100, 100), "SFML window");
Sprite sprite2;
while (app.isOpen())
{
Event event;
while (app.pollEvent(event))
{
if (event.type == Event::Closed)
app.close();
}
app.clear();
sprite2.setTexture(rendertexture.getTexture());
sprite2.setTextureRect(IntRect(0, 0, 64, 64));
app.draw(sprite2);
app.display();
}
return EXIT_SUCCESS;
}
result: red square
#include <SFML/Graphics.hpp>
using namespace sf;
Texture makeTexture()
{
//Block of the same functions
Sprite sprite1;
RenderTexture rendertexture;
rendertexture.create(32, 32);
Image im1;
im1.create(32, 32, Color::Red);
Texture tex1;
tex1.loadFromImage(im1);
sprite1.setTexture(tex1);
sprite1.setPosition(0, 0);
rendertexture.draw(sprite1);
//Block of the same functions
return rendertexture.getTexture();
}
int main()
{
RenderWindow app(VideoMode(100, 100), "SFML window");
Sprite sprite2;
while (app.isOpen())
{
Event event;
while (app.pollEvent(event))
{
if (event.type == Event::Closed)
app.close();
}
app.clear();
sprite2.setTexture(makeTexture());
sprite2.setTextureRect(IntRect(0, 0, 64, 64));
app.draw(sprite2);
app.display();
}
return EXIT_SUCCESS;
}
result: white square!!!
(it's not a joke. Оn my computer 1st code gives red squer, the second gives white)
Why is it so?