Sha256: 4962f7c5292a0495f57b37061250af5183acce9d1335ecc4244b66ed1ff9b7af

Contents?: true

Size: 1.79 KB

Versions: 2

Compression:

Stored size: 1.79 KB

Contents

class AuthorEngine
  class TouchButton
    attr_reader :x, :y, :width, :height
    def initialize(label:, color:, x:, y: nil, width:, height:, side:, for_key: nil, &block)
      @label, @color, @x, @y, @width, @height = label, color, x, y, width, height
      @side, @for_key = side, 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.scale
      @game_x     = `window.innerWidth/2 - #{@game_width/2}`

      if @side == :left
        @x = @game_x-@x
      elsif @side == :right
        @x = @game_x+@game_width+@x
      else
        raise "side must be :left or :right"
      end

      @y = `window.innerHeight/2 - #{height/2}` unless @y.is_a?(Numeric)
    end

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

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

    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

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

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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
author_engine-0.6.1 lib/author_engine/game/opal/touch_button.rb
author_engine-0.6.0 lib/author_engine/game/opal/touch_button.rb