I'm making a game where the character can move in two directions at once - things like up-left, up-right, down-left, etc. This is how I capture multiple keys.
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
//Make a bullet that is going Down at the coordinates of the mouse event
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
mainPlayer.playerDirection = direction::down_right;
}
else {
mainPlayer.playerDirection = direction::down;
}
This is fairly straightforward code and works quite well! I have one problem though.
down_right, up_right, and up_left all work using this method. The problem occurs here:
if (sf::Keyboard::isKeyPressed(sf::Keyboard::S)) {
//Make a bullet that is going Down at the coordinates of the mouse event
if (sf::Keyboard::isKeyPressed(sf::Keyboard::D)) {
mainPlayer.playerDirection = direction::down_right;
cout << "downright";
}
else if (sf::Keyboard::isKeyPressed(sf::Keyboard::A)) {
mainPlayer.playerDirection = direction::down_left;
cout << "down left\n"; //This code NEVER executes. Ever.
}
else {
mainPlayer.playerDirection = direction::down;
}
}
ALL other key combinations work except S and A. I have tried reversing the roles (A first then S), testing different combinations (down arrow and left arrow works just fine). This specific combination of keys does not work for some odd reason. I am stumped and could really use some help. There could be an easy solution staring me in the face, or it may be a bug in 2.4's code. Thanks!
I suggest you separate your if ... elses in two blocks,
Trying to move your character up and down at the same time makes no sense, same for right and left.
Each two opposites actions will figure in the same condition-block, its either this or that but never both
And this will permit to detect 'up to 2 keys-pressed simultaneously' (D or A) and (S or W ) or one of them or nothing of course.
However, it may not be suitable for such : playerDirection variable like in your code. unless you split your playerDirection in two, playerDirection.x and playerDirection.y ( sf::vector2 )
Here is the code if you can adapt it:
if( sf::Keyboard::isKeyPressed(sf::Keyboard::D) ) {
mainPlayer.playerDirection.x = direction::right;
cout << "right";
}else if( sf::Keyboard::isKeyPressed(sf::Keyboard::A) ){
mainPlayer.playerDirection.x = direction::left;
cout << "left";
}
if( sf::Keyboard::isKeyPressed(sf::Keyboard::W) ) {
mainPlayer.playerDirection.y = direction::up;
cout << "up";
}else if( sf::Keyboard::isKeyPressed(sf::Keyboard::S) ){
mainPlayer.playerDirection.y = direction::down;
cout << "down";
}