I am using Windows 10, Visual Studio IDE
I've been trying to experiment with threading in a practice project that I tinker with. I'd like to make a separate thread to handle mouse/keyboard input via a function:
void PlayerInput(sf::RenderWindow& window, float& player_x, float& player_y, float& player_a, float& player_ya) {
if (sf::Mouse::getPosition(window).x < 100) { player_a -= 3.5 * M_PI / 360; }
if (sf::Mouse::getPosition(window).x > 900) { player_a += 3.5 * M_PI / 360; }
if (sf::Mouse::getPosition(window).y < 100) { player_ya += 3.5 * M_PI / 360; }
if (sf::Mouse::getPosition(window).y > 400) { player_ya -= 3.5 * M_PI / 360; }
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
player_x += .08 * cos(player_a);
player_y += .08 * sin(player_a);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
player_x -= .08 * cos(player_a);
player_y -= .08 * sin(player_a);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
player_x -= .08 * cos(player_a + (M_PI / 2));
player_y -= .08 * sin(player_a + (M_PI / 2));
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
player_x -= .08 * cos(player_a - (M_PI / 2));
player_y -= .08 * sin(player_a - (M_PI / 2));
}
...
std::thread thread1(PlayerInput, window, player_x, player_y, player_a, player_ya);
However, whenever I put this into a std::thread, I get several errors like "failed to specialize function template", "no matching overloaded function found", "no overloaded function takes 6 arguments". If I try sf::Thread it complains that 'no instance of constructor "sf::Thread::Thread" matches argument list' " I understand that threads are fairly advanced, but is there an easy explanation for what I'm doing wrong? Is it because the window is one of the arguments? The function works fine outside of a thread.
Thread arguments are passed by value. If you have references, you must therefore wrap them with std::ref.
std::thread thread1(PlayerInput, std::ref(window), std::ref(player_x), std::ref(player_y), std::ref(player_a), std::ref(player_ya));
Note that what you're doing will most likely bring new problems (concurrent access) for no gain ;) But if it's for practicing, ok.