Class: RGame::Engine::Components::WanderController

Inherits:
RGame::Engine::Component show all
Defined in:
lib/rgame/engine/components/wander_controller.rb

Overview

A simple AI driver for a CharacterBody sibling: every so often it rolls a new direction (one of eight, or idle) and holds it until a timer elapses — or until a wall blocks it, at which point it re-rolls early instead of pushing into the wall. The RNG is injected so behaviour is deterministic in tests.

Constant Summary collapse

MOVED_EPS =
1e-6
DIRECTIONS =
[
  [-1, 0], [1, 0], [0, -1], [0, 1],
  [-1, -1], [1, -1], [-1, 1], [1, 1]
].freeze

Instance Attribute Summary

Attributes inherited from RGame::Engine::Component

#node

Instance Method Summary collapse

Methods inherited from RGame::Engine::Component

#context, #control, #draw, #on_detach, #sweep_freed

Methods included from Signal::DSL

#signal

Constructor Details

#initialize(rng: Random.new, change_interval: 1.0..3.0, idle_chance: 0.25) ⇒ WanderController

Returns a new instance of WanderController.



17
18
19
20
21
22
23
# File 'lib/rgame/engine/components/wander_controller.rb', line 17

def initialize(rng: Random.new, change_interval: 1.0..3.0, idle_chance: 0.25)
  super()
  @rng = rng
  @change_interval = change_interval
  @idle_chance = idle_chance
  @timer = 0.0 # rolls a direction on the first update
end

Instance Method Details

#on_attachObject



25
26
27
28
29
# File 'lib/rgame/engine/components/wander_controller.rb', line 25

def on_attach
  @body = node.get_component(CharacterBody)
  @last_x = node.x
  @last_y = node.y
end

#update(dt) ⇒ Object



31
32
33
34
35
36
37
38
# File 'lib/rgame/engine/components/wander_controller.rb', line 31

def update(dt)
  blocked = intending_to_move? && !moved_since_last?
  @last_x = node.x
  @last_y = node.y

  @timer -= dt
  reroll if blocked || @timer <= 0.0
end