-
Hi there, sorry if this is asked a lot, I have written some movement code for a little game, the code works, however on key press, it moves 1 tick of movement, before smoothly moving when held after about a second.
while (this->window->pollEvent(this->ev))
{
switch (this->ev.type)
{
case sf::Event::Closed:
this->window->close();
break;
case sf::Event::KeyReleased:
if (this->ev.key.code == sf::Keyboard::Escape)
{
this->window->close();
}
int i = 0;
if (this->ev.key.code == sf::Keyboard::W)
{
this->players[i].move(0.f, -15);
}
if (this->ev.key.code == sf::Keyboard::A)
{
this->players[i].move(-15, 0.f);
}
if (this->ev.key.code == sf::Keyboard::S)
{
this->players[i].move(0.f, 15);
}
if (this->ev.key.code == sf::Keyboard::D)
{
this->players[i].move(15, 0.f);
}
}
}
My question is if there is a simple way of fixing this so that the movement is smooth immediately. Thanks :)
-
this is due to your keyboard default delay time between keypresses. if you open any text editor and hold a letter like W, you'll notice it behaves exactly the same.
so, for this type of movement, you don't want to use keyboard events. you can use the keyboard global state. instead of
if (this->ev.key.code == sf::Keyboard::W)
use
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
also, your switch statement is a bit messy. why don't you use simply 'if' for now until you get the hang of things?
-
Sorry for the late reply, I tried this and it had the same effect, I noticed a difference when moving diagonally but there I still a pause when using
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
sorry if I'm being dumb but I've been trying to fix this for weeks and I have no idea haha!
-
Nevermind, I borrowed someone else on here's code and switched the variable names and it works. Thanks for your time.
Solution:
while (this->window->pollEvent(this->ev))
{
if (sf::Event::Closed)
{
this->window->close();
break;
}
if (this->ev.key.code == sf::Keyboard::Escape)
{
this->window->close();
}
}
int i = 0;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W)) {
this->players[i].move(0, -3);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
this->players[i].move(0, 3);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
this->players[i].move(-3, 0);
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
this->players[i].move(3, 0);
}
-
ops, I forgot to tell you to move that line outside the event loop. but you did it yourdelf, so i'm glad it worked ;D
-
;D