1
General / Smooth character movement with Arrow keys
« on: February 21, 2023, 06:27:46 pm »
Hey!
I tried making a simple character movement with the arrow keys, just with a rectangle moving around the screen. However, when I press the arrow keys, the rectangle moves similarly to how a text cursor moves between text when the arrow key is held: once for one character, then a pause, then quickly through the rest of the characters. That movement is mimicked by my rectangle, moving once and pausing, then continuing to move after that. I thought I could use a while loop to detect when a key is pressed, but I realized I couldn't because the rest of the program would pause while the key is pressed, so I need to make it with an if statement instead of a while loop. Is there a way to make the movement smooth?
I'm not sure how to display code properly so I am just going to do it like this.
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
rectangle.move(0, -0.5);
y -= 0.05;
cout << x << ", " << y << endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
rectangle.move(0, 0.5);
y += 0.05;
cout << x << ", " << y << endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
rectangle.move(-0.5, 0);
x -= 0.05;
cout << x << ", " << y << endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
rectangle.move(0.5, 0);
x += 0.05;
cout << x << ", " << y << endl;
}
}
I tried making a simple character movement with the arrow keys, just with a rectangle moving around the screen. However, when I press the arrow keys, the rectangle moves similarly to how a text cursor moves between text when the arrow key is held: once for one character, then a pause, then quickly through the rest of the characters. That movement is mimicked by my rectangle, moving once and pausing, then continuing to move after that. I thought I could use a while loop to detect when a key is pressed, but I realized I couldn't because the rest of the program would pause while the key is pressed, so I need to make it with an if statement instead of a while loop. Is there a way to make the movement smooth?
I'm not sure how to display code properly so I am just going to do it like this.
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Up)) {
rectangle.move(0, -0.5);
y -= 0.05;
cout << x << ", " << y << endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Down)) {
rectangle.move(0, 0.5);
y += 0.05;
cout << x << ", " << y << endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Left)) {
rectangle.move(-0.5, 0);
x -= 0.05;
cout << x << ", " << y << endl;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
rectangle.move(0.5, 0);
x += 0.05;
cout << x << ", " << y << endl;
}
}