Welcome, Guest. Please login or register. Did you miss your activation email?

Author Topic: Smooth movement  (Read 2366 times)

0 Members and 1 Guest are viewing this topic.

ArkhamKn1ght

  • Newbie
  • *
  • Posts: 1
    • View Profile
Smooth movement
« on: October 12, 2022, 03:42:15 pm »
Hello. I'm new to SFML and trying to move a circle without repeat delay. The problem is that circle only moves when I press the button, but it stops moving after that(ie it moves only one time, then I have to press the button again). It's weird though that if 'A' is pressed and I start moving cursor on the window the circle starts to move.

#include <SFML/Graphics.hpp>

int main()
{
    sf::RenderWindow window(sf::VideoMode(200, 200), "SFML works!");
    sf::CircleShape shape(100.f);
    shape.setPosition(50.0f, 50.0f);
    shape.setFillColor(sf::Color::Green);
    bool flag = false;
    window.setKeyRepeatEnabled(false);
    while (window.isOpen())
    {
        sf::Event evnt;
        while (window.pollEvent(evnt))
        {
            if (evnt.type == sf::Event::Closed) {
                window.close();
            }
            if (evnt.type == sf::Event::Resized) {
                sf::FloatRect visibleArea(0.f, 0.f, evnt.size.width, evnt.size.height);
                window.setView(sf::View(visibleArea));
            }
            if (evnt.type == sf::Event::KeyPressed) {
                if (evnt.key.code == sf::Keyboard::A) {
                    flag = true;
                }

            }
            if (evnt.type == sf::Event::KeyReleased) {
                if (evnt.key.code == sf::Keyboard::A) {
                    flag = false;
                }
            }
            if (flag) {
                sf::Vector2f movement;
                movement = shape.getPosition();
                movement.x += 5.0f;
                movement.y += 5.0f;
                shape.setPosition(movement);
            }
           
        }
        window.clear();
        window.draw(shape);
        window.display();
    }

    return 0;
}

kojack

  • Sr. Member
  • ****
  • Posts: 343
  • C++/C# game dev teacher.
    • View Profile
Re: Smooth movement
« Reply #1 on: October 12, 2022, 04:25:01 pm »
Your if (flag) block is inside of the event polling while loop, so it can only happen when an event arrives. If you move it out of the loop to just before the window.clear, it will be checked every frame.

 

anything