Hello,
I've just recently tried to check for specific keypress on my keyboard.
Problem is that the statement returns true even if the key, the method supposed to check is not pressed.
In the code bellow you can see I've tried different methods (wich I have commented out) and I have always gotten the same result.
And just for context, I have tried moving a rectangle here.
This is the entire Code.
#include <SFML/Graphics.hpp>
#include "Classes.h"
#include <iostream>
int main()
{
rect.setPosition(rectPos);
rect.setSize(rectSize);
//make the window, but now with extra steps
sf::RenderWindow window(sf::VideoMode(screen.width, screen.height), "This is a window");
window.setFramerateLimit(60);
//main game loop
while (window.isOpen())
{
//event handler
sf::Event event;
while (window.pollEvent(event))
{
if (event.type == sf::Event::Closed)
window.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Escape))
window.close();
if (sf::Keyboard::isKeyPressed(sf::Keyboard::A))
accelLeft = true;
std::cout << "accelLeft is now True\n";
if (sf::Keyboard::isKeyPressed(sf::Keyboard::F))
accelRight = true;
std::cout << "accelRight is now true\n";
if (sf::Event::KeyReleased)
accelLeft = false;
accelRight = false;
std::cout << "A key was released\n";
std::cout << event.key.code << "\n";
}
//apply change in speed
if (accelLeft == true)
rectVel.x -= 0.5;
if (accelRight == true)
rectVel.x += 0.5;
//change rect position relative to its speed
rectPos.x += rectVel.x;
rectPos.y += rectVel.y;
rect.setPosition(rectPos);
//clear everything
window.clear();
//draw
window.draw(rect);
//display changes
window.display();
}
return 0;
}
Code was Edited 1 time
The Result: The rectangle doesnt move
The output even states that with every event that happenes "accelRight" becomes true, even if the event is not pressing the F key.
Any help is much appreciated,
Thanks
Only use the .key.code value of your event when it is relevant: after you have checked that your event type is KeyPressed or KeyReleased, like in the tutorial (https://www.sfml-dev.org/tutorials/2.5/window-events.php#the-keypressed-and-keyreleased-events).
If you don't use curly brackets around your if, only the first instruction following the if will be dependent of the result of your condition.if (event.key.code == 100)
accelRight = true;
std::cout << "accelRight is now true";
This thing you wrote is equivalent to:if (event.key.code == 100) {
accelRight = true;
}
std::cout << "accelRight is now true";
Your std::cout will always be called, whether the if is true or false...
if (sf::Event::KeyReleased)
This doesn't mean anything ??? It's literally like if (6) or whatever the value of the KeyReleased enum is.