Class: RGame::Engine::Components::PathFollow

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

Overview

Walks the owning node along an Engine::Path at a constant speed, segment by segment, and emits on_finished once it reaches the final waypoint — the seam a tower defense game uses to leak a life when an enemy reaches the base.

The walk is allocation-free: it tracks the current segment and the distance into it, advancing through as many segments as one step crosses (so a fast mover over short segments still lands correctly), then interpolates the node's position from the segment endpoints. Movement is driven purely by speed * dt; this is not a Velocity integrator and ignores the node's angle.

Instance Attribute Summary collapse

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(path:, speed:) ⇒ PathFollow

Returns a new instance of PathFollow.



20
21
22
23
24
25
26
27
# File 'lib/rgame/engine/components/path_follow.rb', line 20

def initialize(path:, speed:)
  super()
  @path = path
  @speed = speed
  @segment = 0       # walking from waypoint @segment to @segment + 1
  @distance = 0.0    # distance travelled into the current segment
  @finished = false
end

Instance Attribute Details

#speedObject

Returns the value of attribute speed.



18
19
20
# File 'lib/rgame/engine/components/path_follow.rb', line 18

def speed
  @speed
end

Instance Method Details

#finished?Boolean

Returns:

  • (Boolean)


29
# File 'lib/rgame/engine/components/path_follow.rb', line 29

def finished? = @finished

#on_attachObject

Restart the walk as the node enters the tree — back to the first waypoint, with progress cleared — so a pooled follower reacquired and re-added begins a fresh walk rather than resuming (or staying finished) where its previous life ended.



34
35
36
37
38
39
# File 'lib/rgame/engine/components/path_follow.rb', line 34

def on_attach
  @segment = 0
  @distance = 0.0
  @finished = false
  place_at(0)
end

#update(dt) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/rgame/engine/components/path_follow.rb', line 41

def update(dt)
  return if @finished

  remaining = @speed * dt
  while remaining.positive?
    left = @path.segment_length(@segment) - @distance
    if remaining < left
      @distance += remaining
      break
    end
    # Consume the rest of this segment and step onto the next waypoint.
    remaining -= left
    @segment += 1
    @distance = 0.0
    return finish if @segment >= @path.count - 1
  end
  place_along_segment
end