Module: Chingu::Traits::Timer

Defined in:
lib/chingu/traits/timer.rb

Overview

A chingu trait providing timer-methods to its includer, examples:

during(300) { @color = Color.new(0xFFFFFFFF) }   # forces @color to white ever update for 300 ms
after(400) { self.destroy! }                     # destroy object after 400 ms
between(1000,2000) { self.rotate(10) }           # starting after 1 second, call rotate(10) each update during 1 second

All the above can be combined with a ‘then { do_something }’. For example, a classic shmup damage effect:

during(100) { @color.alpha = 100 }.then { @color.alpha = 255 }

Instance Method Summary collapse

Instance Method Details

#after(time, &block) ⇒ Object



53
54
55
56
57
58
# File 'lib/chingu/traits/timer.rb', line 53

def after(time, &block)
  ms = milliseconds()
  @_last_timer = [ms + time, nil, block]
  @_timers << @_last_timer
  self
end

#between(start_time, end_time, &block) ⇒ Object



60
61
62
63
64
65
# File 'lib/chingu/traits/timer.rb', line 60

def between(start_time, end_time, &block)
  ms = milliseconds()
  @_last_timer = [ms + start_time, ms + end_time, block]
  @_timers << @_last_timer
  self
end

#during(time, &block) ⇒ Object



46
47
48
49
50
51
# File 'lib/chingu/traits/timer.rb', line 46

def during(time, &block)
  ms = milliseconds()
  @_last_timer = [ms, ms + time, block]
  @_timers << @_last_timer
  self
end

#setup_trait(options) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/chingu/traits/timer.rb', line 35

def setup_trait(options)
  @timer_options = {:debug => false}.merge(options)        
  
  #
  # Timers are saved as an array of arrays where each entry contains:
  # [start_time, end_time (or nil if one-shot), &block]
  #
  @_timers = Array.new
  super
end

#then(&block) ⇒ Object



67
68
69
70
71
72
# File 'lib/chingu/traits/timer.rb', line 67

def then(&block)
  # ...use one-shots start_time for our trailing "then".
  # ...use durable timers end_time for our trailing "then".
  start_time = @_last_timer[1].nil? ? @_last_timer[0] : @_last_timer[1]
  @_timers << [start_time, nil, block]
end

#update_traitObject



74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/chingu/traits/timer.rb', line 74

def update_trait
  ms = milliseconds()
  @_timers.each do |start_time, end_time, block|
    if ms > start_time && (end_time == nil || ms < end_time)
      block.call
    end
  end

  # Remove one-shot timers (only a start_time, no end_time) and all timers which have expired
  @_timers.reject! { |start_time, end_time, block| (ms > start_time && end_time == nil) || (end_time != nil && ms > end_time) }
  
  super
end