Input System in Raftel Engine
This tutorial shows how to use Raftel Engine's input system to handle keyboard and mouse interactions.
Input System Basics
The Raftel Engine input system is accessed through the input
member of your window object. Before checking any input, you must update the input system at the beginning of each frame:
// Update at the start of each frame
windowOpt->input->updateKeys();
Keyboard Input
Raftel Engine provides methods to check different key states:
isKeyDown()
Checks if a key is currently held down.
if (windowOpt->input->isKeyDown(Raftel::Input::Keys::Key_W)) {
// W key is down - move forward
}
isKeyUp()
Checks if a key is currently not pressed.
if (windowOpt->input->isKeyUp(Raftel::Input::Keys::Key_W)) {
// W key is up
}
isKeyPressed()
Checks if a key was just pressed this frame.
if (windowOpt->input->isKeyPressed(Raftel::Input::Keys::Key_Space)) {
// Space was just pressed - jump
}
isKeyRelease()
Checks if a key was just released this frame.
if (windowOpt->input->isKeyRelease(Raftel::Input::Keys::Key_Escape)) {
// Escape was just released - toggle menu
}
Mouse Input
Raftel Engine also supports mouse input detection:
Mouse Buttons
if (windowOpt->input->isMouseButtonDown(
Raftel::Input::Buttons::Mouse_Left)) {
// Left mouse button is being held down
}
Mouse Position
glm::vec2 mousePos = windowOpt->input->getMousePosition();
// mousePos.x and mousePos.y contain coordinates
Mouse Movement
glm::vec2 mouseDelta = windowOpt->input->getMouseDelta();
// mouseDelta.x and mouseDelta.y contain movement
Mouse Wheel
glm::vec2 scrollDelta = windowOpt->input->getScrollDelta();
// scrollDelta.y contains vertical scroll amount
Example: Moving a Shape with Keyboard
This example shows how to move a triangle with WASD keys and rotate it with Q and E:
// Set up direction vector
Raftel::Vec2 dir = {0, 0};
const float speed = 0.5f;
// Check WASD keys for movement
if (windowOpt->input->isKeyDown(Raftel::Input::Keys::Key_W)) {
dir.y = speed; // Move up
}
if (windowOpt->input->isKeyDown(Raftel::Input::Keys::Key_A)) {
dir.x = -speed; // Move left
}
if (windowOpt->input->isKeyDown(Raftel::Input::Keys::Key_D)) {
dir.x = speed; // Move right
}
if (windowOpt->input->isKeyDown(Raftel::Input::Keys::Key_S)) {
dir.y = -speed; // Move down
}
// Check Q and E for rotation
if (windowOpt->input->isKeyDown(Raftel::Input::Keys::Key_Q)) {
triangle.tr.Rotate(angle * deltaTime); // Rotate counter-clockwise
}
if (windowOpt->input->isKeyDown(Raftel::Input::Keys::Key_E)) {
triangle.tr.Rotate(-angle * deltaTime); // Rotate clockwise
}
// Apply movement
triangle.tr.velocity_ = dir;
triangle.tr.Translate(deltaTime);
Next Steps
Loading 3D Meshes
Learn how to load and render 3D models in your application.
Input System API
View the full API reference for the Input system.
For complete details, see the Input API Reference.