Class: Graphics::Trail

Inherits:
Object
  • Object
show all
Defined in:
lib/graphics/trail.rb

Overview

A simple “trail” class, that draws the path of a in a particular hue.

# ... in initialize
self.trail = Trail.new self, 100, :white

# ... in Body#update
trail << body

# ... in Body#draw
trail.draw

Constant Summary collapse

@@c =
{}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(w, max, color = :green) ⇒ Trail

Create a Trail with max length and of a particular color hue.



41
42
43
44
45
46
47
48
49
# File 'lib/graphics/trail.rb', line 41

def initialize w, max, color = :green
  self.w = w
  self.a = []
  self.max = max
  unless @@c[color] then
    @@c[color] ||= (0..99).map { |n| ("%s%02d" % [color, n]).to_sym }.reverse
  end
  self.c = @@c[color]
end

Instance Attribute Details

#aObject

The array of x/y coordinates of the trail.



21
22
23
# File 'lib/graphics/trail.rb', line 21

def a
  @a
end

#cObject

The hues to draw in the trail.



36
37
38
# File 'lib/graphics/trail.rb', line 36

def c
  @c
end

#maxObject

The maximum number of segments to keep in the trail.



31
32
33
# File 'lib/graphics/trail.rb', line 31

def max
  @max
end

#wObject

The windowing system we’re drawing in.



26
27
28
# File 'lib/graphics/trail.rb', line 26

def w
  @w
end

Instance Method Details

#<<(body) ⇒ Object

Add another segment to the trail, and remove a segment if needed.



64
65
66
67
68
# File 'lib/graphics/trail.rb', line 64

def << body
  a << [body.x, body.y]
  a.shift if a.size > max
  nil
end

#drawObject

Draw the trail and taper off the color as we go.



54
55
56
57
58
59
# File 'lib/graphics/trail.rb', line 54

def draw
  m = 100.0 / max
  a.reverse_each.each_cons(2).with_index do |((x1, y1), (x2, y2)), i|
    w.line x1, y1, x2, y2, c[(i*m).round] || :black
  end
end