Quellcode durchsuchen

Add key events;

bjorn vor 7 Jahren
Ursprung
Commit
c1d343c390
3 geänderte Dateien mit 30 neuen und 4 gelöschten Zeilen
  1. 2 0
      README.md
  2. 18 2
      lovr-keyboard.lua
  3. 10 2
      main.lua

+ 2 - 0
README.md

@@ -22,6 +22,8 @@ API
 
 - `keyboard.isDown(key)` Returns whether or not the specified key is down.  Currently letters,
   numbers, and 'space' are supported.
+- `lovr.keypressed(key)` Called when a key is pressed.
+- `lovr.keyreleased(key)` Called when a key is released.
 
 License
 ---

+ 18 - 2
lovr-keyboard.lua

@@ -3,8 +3,11 @@ local C = ffi.os == 'Windows' and ffi.load('glfw3') or ffi.C
 
 ffi.cdef [[
   typedef struct GLFWwindow GLFWwindow;
+  typedef void(*GLFWkeyfun)(GLFWwindow*, int, int, int, int);
+
   GLFWwindow* glfwGetCurrentContext(void);
   int glfwGetKey(GLFWwindow* window, int key);
+  GLFWkeyfun glfwSetKeyCallback(GLFWwindow* window, GLFWkeyfun callback);
 ]]
 
 local window = C.glfwGetCurrentContext()
@@ -126,11 +129,24 @@ local keymap = {
   ['menu'] = 348
 }
 
+for k, v in pairs(keymap) do
+  keymap[v] = k
+end
+
+local function keyCallback(window, key, scancode, action, mods)
+  if action ~= 2 and keymap[key] then
+    lovr.event.push(action > 0 and 'keypressed' or 'keyreleased', keymap[key])
+  end
+end
+
+C.glfwSetKeyCallback(window, keyCallback)
+
 local keyboard = {}
 
 function keyboard.isDown(key)
-  if not keymap[key] then error('Unknown key: ' .. key) end
-  return C.glfwGetKey(window, keymap[key]) == 1
+  local keycode = key and keymap[key]
+  assert(keycode and type(keycode) == 'number', 'Unknown key: ' .. key)
+  return C.glfwGetKey(window, keycode) == 1
 end
 
 return keyboard

+ 10 - 2
main.lua

@@ -1,7 +1,15 @@
 lovr.keyboard = require 'lovr-keyboard'
 
+function lovr.keypressed(key)
+  print('keypressed', key)
+end
+
+function lovr.keyreleased(key)
+  print('keyreleased', key)
+end
+
 function lovr.update(dt)
-  if lovr.keyboard then
-    print(lovr.keyboard.isDown('space'))
+  if lovr.keyboard.isDown('space') then
+    print('I just need some space')
   end
 end