C++ Mouse & Keyboard Input
In this page:
Keyboard Input with sf::Keyboard
sf::Keyboard::isKeyPressed(key) checks the current, real-time state of a specific key at the moment you call it, independent of the event queue -- ideal for continuous actions like "move right while held," since it doesn't require the key to have just changed state.
Example: Keyboard Input with sf::Keyboard
#include <SFML/Window.hpp>
int main() {
if (sf::Keyboard::isKeyPressed(sf::Keyboard::Right)) {
// move right while the key is held
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Handling Keyboard Events
Keyboard events delivered through the event loop (KeyPressed/KeyReleased) fire exactly once per press or release, rather than continuously while held -- this makes them the right choice for discrete, one-shot actions like "jump" or "open menu," where you don't want the action repeating every frame the key stays down.
Example: Handling Keyboard Events
#include <SFML/Graphics.hpp>
int main() {
sf::RenderWindow window(sf::VideoMode(400, 300), "Events");
sf::Event event;
while (window.pollEvent(event)) {
if (event.type == sf::Event::KeyPressed)
; // fires exactly once per press, good for "jump"
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Mouse Position Tracking
sf::Mouse::getPosition() returns the cursor's current pixel coordinates, either relative to the whole screen or, when passed a window reference, relative to that window's client area -- useful for anything that needs to know exactly where on screen the player is pointing.
Example: Mouse Position Tracking
#include <SFML/Window.hpp>
int main() {
sf::Vector2i screenPos = sf::Mouse::getPosition();
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Mouse Click Events
Like keyboard state, sf::Mouse::isButtonPressed() reports whether a mouse button is currently held down at the moment you ask, while the event loop's MouseButtonPressed event reports a single click -- choose whichever matches whether you need continuous or one-shot behavior.
Example: Mouse Click Events
#include <SFML/Window.hpp>
int main() {
if (sf::Mouse::isButtonPressed(sf::Mouse::Left)) {
// continuously true while held down
}
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Collision and Selection
getGlobalBounds() returns a shape's bounding rectangle in world coordinates, and calling .contains(mousePosition) on it tells you whether the cursor is currently over that shape -- the standard building block for clickable buttons or drag-and-select interactions.
Example: Collision and Selection
#include <SFML/Graphics.hpp>
int main() {
sf::CircleShape shape(30.f);
sf::Vector2f mousePos(35.f, 35.f);
bool hovered = shape.getGlobalBounds().contains(mousePos);
return 0;
}
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: