aboutsummaryrefslogtreecommitdiff
path: root/src/input.lua
blob: 8029be24b56f4b792d73677643700aec734c6feb (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
local lk = love.keyboard
local lm = love.mouse

local inputs = {}
local keyEvents = {}
local mouseEvents = {}

---@param triggers table pair like this {type, keycode/name}
function register_input(name, triggers)
  inputs[name] = triggers
end

function input_direction(left, right, up, down)
  return bton(is_input_pressed(right)) - bton(is_input_pressed(left)),
    bton(is_input_pressed(down)) - bton(is_input_pressed(up))
end

function is_input_just_pressed(name)
  local inp = inputs[name]
  local type
  local code

  for _, trig in ipairs(inp) do
    type = trig[1]
    code = trig[2]

    if type == "mouse" then
      if mouseEvents[code] ~= nil then return true end
    end
    if type == "key" then
      if keyEvents[code] ~= nil then return true end
    end
  end
end

function is_input_pressed(name)
  local inp = inputs[name]
  local type
  local code

  for _, trig in ipairs(inp) do
    type = trig[1]
    code = trig[2]

    if type == "mouse" then
      if lm.isDown(code) then return true end
    end
    if type == "key" then
      if lk.isDown(code) then return true end
    end
  end
end

function love.keypressed(key)
  keyEvents[key] = true
end

function love.mousepressed(x, y, btn)
  mouseEvents[btn] = true
end

function get_mouse_pos()
  -- TODO: Fix mouse position relative to games canvas
  local scrw, scrh = love.graphics.getDimensions()
  return math.floor(lm.getX() / scrw * SCR_WIDTH), math.floor(lm.getY() / scrh * SCR_HEIGHT)
end

function input_step()
  for key in pairs(keyEvents) do
    keyEvents[key] = nil
  end
  for key in pairs(mouseEvents) do
    mouseEvents[key] = nil
  end
end