-
My camera movment works, however, if I hold the the 'S' key (down) it will move the camera down as i want to, but then if I hold 'W' after holding 'S' it will always go up. I tried many ways to fix this, all were not working and just confusing. Can you guys help me improve this code?
extern float deltaTime;
int hor = 0;
int ver = 0;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
ver = 1;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
ver = -1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
hor = -1;
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
hor = 1;
}
if (hor != 0 || ver != 0)
view.move(speed * hor * deltaTime, speed * -ver * deltaTime);
//y value is inverted, camera works with +y being down and -y being up
hor is a number to store the direction in the horizontal axis.
ver is a number to store the direction in the vertical axis.
-
Hard to tell what really goes on since it's just a random code snippet, but what you most likely want to add is a third condition to vertical and one to horizontal movement and that is, if both keys are pressed at the same time, the movement should stop.
-
Oh yeah, I didn't think about that. That would be the fastest and easiest way to solve my problem for now. Thanks
edit: new code: thought of a way to do it without a 3rd condition
int hor = 0;
int ver = 0;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
{
ver = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
{
ver--;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
{
hor = 1;
}
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
{
hor--;
}
-
Since you're setting them both to zero beforehand, it could be more readable to also use increment as well:
int hor = 0;
int ver = 0;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::W))
++ver;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S))
--ver;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D))
++hor;
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
--hor;
Also note that W and D (up and right) are both positive here. Depending on what you're trying to achieve, you may wish to invert one of them (horizontal or vertical).
(I actually used this method (https://github.com/Hapaxia/BringItBack/blob/master/functions.cpp?ts=4#L28-L36) for my SFML game jam entry)