Class: Lotu::InputController

Inherits:
Object
  • Object
show all
Defined in:
lib/lotu/behaviors/controllable/input_controller.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(subject, keys) ⇒ InputController

Returns a new instance of InputController.



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
# File 'lib/lotu/behaviors/controllable/input_controller.rb', line 5

def initialize(subject, keys)
  # The subject being controlled
  @subject = subject

  # Key mappings {Gosu::Button::KbEscape => :quit, ...}
  @keys = keys

  # Current ongoing actions (button is being pushed)
  @actions = []
  @once_actions = []

  # Last time an action was executed (so we can implement some
  # rate of fire)
  @executed_at = {}

  # Register this controller with the main window
  $window.register_for_input(self)
end

Instance Attribute Details

#keysObject

Returns the value of attribute keys.



3
4
5
# File 'lib/lotu/behaviors/controllable/input_controller.rb', line 3

def keys
  @keys
end

#subjectObject

Returns the value of attribute subject.



3
4
5
# File 'lib/lotu/behaviors/controllable/input_controller.rb', line 3

def subject
  @subject
end

Instance Method Details

#button_down(id) ⇒ Object



41
42
43
44
45
46
47
48
49
# File 'lib/lotu/behaviors/controllable/input_controller.rb', line 41

def button_down(id)
  action_name, rate = @keys[id]
  @executed_at[action_name] ||= 0
  if rate == false
    @once_actions << @keys[id]
  else
    @actions << @keys[id]
  end
end

#button_up(id) ⇒ Object



51
52
53
# File 'lib/lotu/behaviors/controllable/input_controller.rb', line 51

def button_up(id)
  @actions.delete(@keys[id])
end

#updateObject

If there are some actions currently going on, dispatch them



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/lotu/behaviors/controllable/input_controller.rb', line 25

def update
  @once_actions.each do |action_name, rate|
    @subject.send(action_name)
  end.clear

  @actions.each do |action_name, rate|
    # action usually is a [:action_name, rate_of_fire] pair, for
    # example: [:fire, 50] will call #fire every 50ms
    time_now = Gosu.milliseconds
    if @executed_at[action_name] + (rate || 0) < time_now
      @executed_at[action_name] = time_now
      @subject.send(action_name)
    end
  end
end