I'm new to SFML and C++ in general, reading a few texts while playing around with code to keep things fun. My first goal is to get some really basic code into an object oriented shape so that I can see a gameloop, keystrokes, and some simple draws all working together.
I started with the code from the setup tutorial, and it drew my little 200x200 window & green circle just fine. So I started moving stuff around to get that .draw() and .display() into its own thread under a block that fires off every-so-often.
I got to a state where the block executes, but for some reason the window.display() doesn't seem to do anything.
My OutputDebug lines all fire off, so I can see that the program is looping and executing on separate threads. In debugging mode, I can see it execute the .display() but it just leaves the window blank white. On the next line, I added a window.setTitle to make sure that the thread could talk to my window object--and that succeeds. If I take the window.display() back into main(), it draws successfully. So is the problem from the threading? From not using SFML's window.setFramerateLimit(60) with main()? I'm quite confused.
I know this code is probably ugly in a lot of ways. I just want to see the gears turning with each other for now.
(But with that said, I always appreciate free opinions & information)
// (some includes)
extern float posX = 0;
extern float posY = 0;
int keepGoing = 0;
sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
sf::CircleShape shape(100.f);
auto gameStart = std::chrono::high_resolution_clock::now();
auto lastDraw = gameStart;
auto nextDraw = lastDraw;
void draw()
{
if (GetKeyState('D') == true){ posX++; }
if (GetKeyState('A') == true){ posX--; }
shape.setPosition(posX, posY);
window.clear();
window.draw(shape);
window.display(); //Here's the RenderWindow.display()
window.setTitle("TITLE RESET"); //This succeeds, so I do have access to "window"
OutputDebugString(L"\nDrawing!"); //I can see that this successfully executes, so I know the code is getting to here
}
//this runloop just calls my draw() every so often. My main() hands this loop the draw() function as *fp
void runloop(void (*fp)())
{
while (keepGoing == 1)
{
OutputDebugString(L"\nLooping!");
fp();
lastDraw = std::chrono::high_resolution_clock::now();
nextDraw += std::chrono::milliseconds(15);
std::this_thread::sleep_until(nextDraw);
}
}
int main()
{
shape.setFillColor(sf::Color::Green);
keepGoing = 1;
void (*drawp)();
drawp = draw;
std::thread t1(runloop,drawp);
while (window.isOpen())
{
sf::Event event;
OutputDebugString(L"\nGotHere!");
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
}
// Here's where the RenderWindow.display() is in the tutorial
}
return 0;
}