Sha256: 71b6c30c2ea82536529b9e8077ce9673c3d4c7ad0386596892a8c687bf55e31d

Contents?: true

Size: 1.5 KB

Versions: 3

Compression:

Stored size: 1.5 KB

Contents

module Tsuku
  class Tween
    def initialize(target, final_property_values, duration_ms, easing = :linear)
      @target = target
      @final_property_values = final_property_values
      @duration_ms = duration_ms
      @easing = easing

      @running = false
      @elapsed_ms = 0.0
    end
    
    def start
      @initial_property_values = {}

      @final_property_values.each_key do |k|
        @initial_property_values[k] = @target.send(k)
      end

      @running = true
    end

    def step(delta_ms)    
      return if !@running
      
      @elapsed_ms += delta_ms

      if @elapsed_ms >= @duration_ms
        complete
        return
      end

      advance_property_values
    end

    def pause
      @running = false
    end

    def resume
      @running = true unless completed?
    end

    def reset
      @elapsed_ms = 0
    end

    def completed?
      @elapsed_ms >= @duration_ms
    end

    private
    
    def advance_property_values
      @final_property_values.each_key do |k|
        # Based on Penner's equations
        t = @elapsed_ms
        b = @initial_property_values[k]
        c = @final_property_values[k] - @initial_property_values[k]
        d = @duration_ms
        
        current_value = Easing.method(@easing).call(t, b, c, d)
        
        @target.send("#{k}=", current_value)
      end
    end

    def complete
      @elapsed_ms = @duration_ms
      
      @final_property_values.each do |k,v|
        @target.send("#{k}=", v)
      end

      @running = false
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
tsuku-0.2.0 lib/tsuku/tween.rb
tsuku-0.1.2 lib/tsuku/tween.rb
tsuku-0.1.1 lib/tsuku/tween.rb