The input module of a game engine deals with most input from users, such as the keyboard, mouse, buttons, and so on. It builds a bridge between external input and the engine’s internal functionality.
It usually figures out all the important information about an input signal. For key input, we need to determine whether it is pressed or released, and how many times it is repeatedly pressed. For mouse input, we need to figure out the button code and the position of the cursor. Additionally, the Input class must be a static class so that its methods can be called outside of the class.
Implementation
Based on the information above, we can create a file called Input.h inside the Illusion/src/Engine/Core/Input/… folder and enter:
// Static methods that could be used outside of this class // Call the virtual function that would be implemented in the inhirated class staticboolIsKeyPressed(int keycode);
All methods in the Input class are static, so they can be called using code like: Illusion::Input::FunctionName(Argument list) without declaring any instance of Input class.
Under the definition of the Input class, we’ve defined a list of macros that represent the keycode and mouse button codes. The values of these codes correspond to those in the GLFW library, allowing us to use these macros in our code instead of those from the GLFW library.
To implement these methods, we need to use the interfaces provided by the GLFW library. Inside the same folder, create a file called Input.cpp and enter:
boolInput::IsKeyPressed(int keycode) { auto window = Application::Get().GetWindow().GetNativeWindow(); auto state = glfwGetKey(window, keycode); return state == GLFW_PRESS || state == GLFW_REPEAT; }
boolInput::IsMouseButtonPressed(int button) { auto window = Application::Get().GetWindow().GetNativeWindow(); auto state = glfwGetMouseButton(window, button); return state == GLFW_PRESS; }
We use Application::Get() to obtain the application instance, then .GetWindow() to get the previously defined window wrapper, and finally .GetNativeWindow() to get the GLFW window instance.
Utilization
To integrate the input module into the engine, we need to include the header file inside Engine.h.
There are two ways to use the Input module in the code:
Use the code defined with Event dispatcher.
Simply use the functions provided in the module.
For case 1, you can revise the TestLayer like this:
#include"TestLayer.h" TestLayer::TestLayer() :Layer("TestLayer"), m_CameraController(2560.0f / 1440.0f, true) {} voidTestLayer::OnAttach(){} voidTestLayer::OnDetach(){} voidTestLayer::OnUpdate(Illusion::Timestep timestep) { // Render // Set the clear color // Clear the color buffer with the clear color glClearColor(0.3f, 0.3f, 0.3f, 1.0f); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);