1
\$\begingroup\$

I'm new to game development and making a Pong clone in SFML. I am trying to set the screen's top and bottom as bounds for the paddle.

Here is my attempt:

#include "main.h"
#include "objects.h"

int main()
{
sf::RenderWindow window(sf::VideoMode(900, 600), "Pong");
window.setVerticalSyncEnabled(true);
initData();
while (window.isOpen())
{        
#pragma region Event Handling
    sf::Event event;
    while (window.pollEvent(event))
    {
        switch (event.type)
        {
        case sf::Event::Closed:
            window.close();
            break;
        default:
            break;
        }
    if (sf::Mouse::getPosition(window).y <= 500 &&  sf::Mouse::getPosition(window).y >= 0)
    {
        player1paddle.setPosition(100, sf::Mouse::getPosition(window).y);
    }
    }
 #pragma endregion
 #pragma region Rendering
    window.clear(sf::Color::Black);
    window.draw(net);
    window.draw(player1paddle);
    window.draw(aipaddle);
    window.display();
 #pragma endregion
}

    return 0;
}

The problem: When I move the mouse fast, the sprite stops moving before it hits the bottom. I'm assuming this is caused by the mouse moving faster than the loop is running. Is there a faster/more efficient way to do this?

\$\endgroup\$
2
\$\begingroup\$

Your problem is that mouse move events are discrete.

For example, slowly moving the cursor over 50 pixels, might get you 5, 10, 15 or more mouse move events. However, if you move your cursor fast, it's possible to get only one mouse move event for the entire distance or possibly none at all (if the target point is outside your window).

This is something you can't really change, unless by trapping the cursor inside your window (also known as clipping or wrapping the cursor). Unfortunately, this functionality isn't exposed by SFML so far, though there is an open issue regarding it.

What you can do as a work-around:

  • Whenever there is a mouse move event, move the cursor back to the center of the window.
  • The distance travelled can be used to determine the paddle movement.
  • Just keep in mind to not do this if your window isn't the active forgeground window (this can be tricky; there's going to be some new API method in SFML 2.2 to make this easier).
\$\endgroup\$
1
  • \$\begingroup\$ @Narrateurduchaos That suggested edit deserves an answer by itself. \$\endgroup\$
    – Vaillancourt
    Jan 21 '18 at 1:38

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.