From 6de3d16fd3e7d98c98cdf73c6a3317e1a6b10184 Mon Sep 17 00:00:00 2001 From: Adrian Kummerlaender Date: Sat, 26 May 2018 23:15:02 +0200 Subject: Add KeyWatcher to handle pausing via space --- src/glfw/key_watcher.cc | 24 ++++++++++++++++++++++++ src/glfw/key_watcher.h | 17 +++++++++++++++++ src/glfw/window.cc | 4 ++++ src/glfw/window.h | 8 ++++++-- 4 files changed, 51 insertions(+), 2 deletions(-) create mode 100644 src/glfw/key_watcher.cc create mode 100644 src/glfw/key_watcher.h (limited to 'src/glfw') diff --git a/src/glfw/key_watcher.cc b/src/glfw/key_watcher.cc new file mode 100644 index 0000000..21a570a --- /dev/null +++ b/src/glfw/key_watcher.cc @@ -0,0 +1,24 @@ +#include "key_watcher.h" + +KeyWatcher::KeyWatcher(GLFWwindow* handle, int key): + _handle(handle), + _key(key), + _last_state(glfwGetKey(_handle, _key)) +{ } + +bool KeyWatcher::wasClicked() { + switch ( glfwGetKey(_handle, _key) ) { + case GLFW_RELEASE: + _last_state = GLFW_RELEASE; + return false; + case GLFW_PRESS: + if ( _last_state == GLFW_RELEASE ) { + _last_state = GLFW_PRESS; + return true; + } else { + return false; + } + default: + return false; + } +} diff --git a/src/glfw/key_watcher.h b/src/glfw/key_watcher.h new file mode 100644 index 0000000..538829f --- /dev/null +++ b/src/glfw/key_watcher.h @@ -0,0 +1,17 @@ +#pragma once + +#include + +class KeyWatcher { +private: + GLFWwindow* const _handle; + + int _key; + int _last_state; + +public: + KeyWatcher(GLFWwindow* handle, int key); + + bool wasClicked(); + +}; diff --git a/src/glfw/window.cc b/src/glfw/window.cc index 17fc36c..6fbbfee 100644 --- a/src/glfw/window.cc +++ b/src/glfw/window.cc @@ -22,3 +22,7 @@ int Window::getWidth() const { int Window::getHeight() const { return _height; } + +KeyWatcher Window::getKeyWatcher(int key) { + return KeyWatcher(_handle, key); +} diff --git a/src/glfw/window.h b/src/glfw/window.h index b858e9a..520b5e8 100644 --- a/src/glfw/window.h +++ b/src/glfw/window.h @@ -5,6 +5,8 @@ #include #include +#include "key_watcher.h" + class Window { private: bool _good = false; @@ -21,6 +23,8 @@ public: int getWidth() const; int getHeight() const; + KeyWatcher getKeyWatcher(int key); + template void init(F f); @@ -39,8 +43,8 @@ template void Window::render(F loop) { glfwMakeContextCurrent(_handle); - while ( glfwGetKey(_handle, GLFW_KEY_ESCAPE ) != GLFW_PRESS && - glfwWindowShouldClose(_handle) == 0 ) { + while ( glfwGetKey(_handle, GLFW_KEY_ESCAPE) != GLFW_PRESS && + glfwWindowShouldClose(_handle) == 0 ) { glfwGetWindowSize(_handle, &_width, &_height); loop(); -- cgit v1.2.3