Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Support for custom Key Callbacks in Input class #53

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions Walnut/src/Walnut/Input/Input.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,31 @@

namespace Walnut {

std::unordered_map<int, std::function<void()>> Input::s_KeyCallbackMap;

void KeyCallback(GLFWwindow* window, int key, int scancode, int action, int mods)
{
if (action == GLFW_PRESS || action == GLFW_REPEAT)
{
auto funcIter = Input::s_KeyCallbackMap.find(key);
if (funcIter != Input::s_KeyCallbackMap.end())
{
funcIter->second();
}
}
}

void Input::InitKeysCallBack()
{
GLFWwindow* windowHandle = Application::Get().GetWindowHandle();
glfwSetKeyCallback(windowHandle, KeyCallback);
}

void Input::SetKeyCallback(KeyCode keycode, std::function<void()> func)
{
s_KeyCallbackMap[(int)keycode] = func;
}

bool Input::IsKeyDown(KeyCode keycode)
{
GLFWwindow* windowHandle = Application::Get().GetWindowHandle();
Expand Down
9 changes: 9 additions & 0 deletions Walnut/src/Walnut/Input/Input.h
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,28 @@

#include "KeyCodes.h"

#include <functional>
#include <unordered_map>
#include <glm/glm.hpp>

namespace Walnut {

class Input
{
public:
static void InitKeysCallBack();

static void SetKeyCallback(KeyCode keycode, std::function<void()> func);

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I would suggest to pass the KeyCode to the callback, so that one function could be used for multiple keys.


static bool IsKeyDown(KeyCode keycode);

static bool IsMouseButtonDown(MouseButton button);

static glm::vec2 GetMousePosition();

static void SetCursorMode(CursorMode mode);

static std::unordered_map<int, std::function<void()>> s_KeyCallbackMap;
};

}