Class: AuthorEngine::TouchButton

Inherits:
Object
  • Object
show all
Defined in:
lib/author_engine/game/opal/touch_button.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(label:, color:, x: 0, y: 0, width:, height:, for_key: nil, &block) ⇒ TouchButton

Returns a new instance of TouchButton.



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/author_engine/game/opal/touch_button.rb', line 5

def initialize(label:, color:, x: 0, y: 0, width:, height:, for_key: nil, &block)
  @label, @color, @x, @y, @width, @height = label, color, x, y, width, height
  @for_key = for_key
  @block = block

  @buttons    = AuthorEngine::Part::OpalInput::BUTTONS
  @key_states = AuthorEngine::Part::OpalInput::KEY_STATES

  @game       = AuthorEngine::GameRunner.instance.game
  @game_width = 128 * @game.authorengine_scale
  @game_x     = `window.innerWidth/2 - #{@game_width/2}`
end

Instance Attribute Details

#heightObject (readonly)

Returns the value of attribute height.



4
5
6
# File 'lib/author_engine/game/opal/touch_button.rb', line 4

def height
  @height
end

#widthObject (readonly)

Returns the value of attribute width.



4
5
6
# File 'lib/author_engine/game/opal/touch_button.rb', line 4

def width
  @width
end

#xObject

Returns the value of attribute x.



3
4
5
# File 'lib/author_engine/game/opal/touch_button.rb', line 3

def x
  @x
end

#yObject

Returns the value of attribute y.



3
4
5
# File 'lib/author_engine/game/opal/touch_button.rb', line 3

def y
  @y
end

Instance Method Details

#activeObject



49
50
51
# File 'lib/author_engine/game/opal/touch_button.rb', line 49

def active
  @key_states[@buttons[@for_key]] = true
end

#drawObject



18
19
20
21
22
23
24
25
26
27
# File 'lib/author_engine/game/opal/touch_button.rb', line 18

def draw
  `#{@game.authorengine_canvas_context}.fillStyle = #{@color}`
  `#{@game.authorengine_canvas_context}.fillRect(#{@x}, #{@y}, #{@width}, #{@height})`

  font = "#{@height}px Connection, Consolas"
  `#{@game.authorengine_canvas_context}.font = #{font}`
  `#{@game.authorengine_canvas_context}.fillStyle = "white"`
  `#{@game.authorengine_canvas_context}.textBaseline = "top"`
  `#{@game.authorengine_canvas_context}.fillText(#{@label}, #{@x}, #{@y}, #{@width})`
end

#inactiveObject



53
54
55
# File 'lib/author_engine/game/opal/touch_button.rb', line 53

def inactive
  @key_states[@buttons[@for_key]] = false
end

#trigger?(touches) ⇒ Boolean

Returns:

  • (Boolean)


29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/author_engine/game/opal/touch_button.rb', line 29

def trigger?(touches)
  triggered = false

  touches.detect do |id, touch|
    if touch.x.between?(@x, @x+@width) && touch.y.between?(@y, @y+@height)
      triggered = true
    end
  end


  if @for_key
    active if triggered
    inactive unless triggered
  else
    @block.call if @block && triggered
  end

  return triggered
end