Module: SFML::InputActions

Included in:
App, Scene
Defined in:
lib/sfml/input_actions.rb

Overview

Class-level action DSL — named bindings over multiple physical inputs. Shared by SFML::App and SFML::Scene. Pairs with the Keybindings mixin: keybindings fire events (one-shot, on press), actions are polled state ("is the user holding this right now?").

class MyGame < SFML::App
action :jump,    keys: [:space, :w]
action :fire,    mouse_buttons: [:left]
action :left,    keys: [:a, :left],    scancodes: [:scan_a]
action :right,   keys: [:d, :right]
action :crouch,  joy_buttons: [[0, 0]]  # joystick 0, button 0

def update(dt)
  speed = 200 * dt.as_seconds
  @x += speed if action_pressed?(:right)
  @x -= speed if action_pressed?(:left)
  @ball.jump if action_pressed?(:jump)
end
end

Keys are mapped via SFML::Keyboard.key_pressed? — the logical key under the current OS layout. Scancodes are mapped via SFML::Keyboard.scancode_pressed? — the physical position (recommended for WASD-style movement so the keys stay under the same fingers across layouts).

axis(:name) is a convenience for digital pairs: pass negative: and positive: actions and you get a Float in [-1, 1].

class Player < SFML::App
action :go_left,  keys: [:a, :left]
action :go_right, keys: [:d, :right]

def update(dt)
  move = axis(negative: :go_left, positive: :go_right)
  @x += move * 200 * dt.as_seconds
end
end

Instance Method Summary collapse

Instance Method Details

#action(name, keys: [], scancodes: [], mouse_buttons: [], joy_buttons: []) ⇒ Object

Class-side: declare a named action.

Parameters:

  • name (Symbol) —

    action identifier

  • keys (Array<Symbol>) (defaults to: []) —

    logical key symbols (see Keyboard::KEY_CODES)

  • scancodes (Array<Symbol>) (defaults to: []) —

    physical scancode symbols (see Keyboard::SCAN_CODES)

  • mouse_buttons (Array<Symbol>) (defaults to: []) —

    :left / :right / :middle / :extra1 / :extra2

  • joy_buttons (Array<Array<Integer>>) (defaults to: []) —

    [[joystick_id, button_id], ...]



49
50
51
52
53
54
55
56
57
# File 'lib/sfml/input_actions.rb', line 49

def action(name, keys: [], scancodes: [], mouse_buttons: [], joy_buttons: [])
  @action_bindings ||= {}
  @action_bindings[name.to_sym] = {
    keys:          Array(keys).map(&:to_sym),
    scancodes:     Array(scancodes).map(&:to_sym),
    mouse_buttons: Array(mouse_buttons).map(&:to_sym),
    joy_buttons:   Array(joy_buttons).map { |pair| Array(pair).map(&:to_i) },
  }
end

#action_bindings ⇒ Object

Hash{action_name => bindings} — own bindings layered over the parent's. Subclass action calls add to the inherited set.



61
62
63
64
65
# File 'lib/sfml/input_actions.rb', line 61

def action_bindings
  own    = (@action_bindings ||= {})
  parent = superclass.respond_to?(:action_bindings) ? superclass.action_bindings : {}
  parent.merge(own)
end