查看: 5059|回复: 2

[原创发布] 【RM】Timer定时器/定时执行脚本v2.9

[复制链接]
梦石
0
星屑
19426
在线时间
3082 小时
注册时间
2013-1-11
回帖
1207
发表于 2018-9-2 12:30:03 | 显示全部楼层 |阅读模式

加入我们,或者,欢迎回来。

您需要 登录 才可以下载或查看,没有账号?注册会员

×
本帖最后由 张咚咚 于 2022-1-22 12:02 编辑

脚本内容
  1. #encoding:utf-8
  2. #==============================================================================
  3. # ■ 定时器v3.0 By_QQEat ————2022.01.16
  4. #
  5. #   说明:定时执行脚本, tween 动画等。
  6. #
  7. #   [创建、释放等基础方法]
  8. #
  9. #     @timer = Timer.new      # 创建
  10. #     @timer.update(tag=nil)  # 更新(传标签参数后, 则只更新指定标签的任务)
  11. #     @timer.dispose          # 释放
  12. #     @timer.disposed?        # 是否已释放?
  13. #     @timer.clear            # 清空计时任务
  14. #     @timer.timer            # 查看所有任务
  15. #
  16. #   [添加任务]
  17. #     
  18. #     @timer.cancel(*tags)  # 删除定时任务(支持正则表达式)
  19. #     @timer.after(delay, action, tag=nil)
  20. #     @timer.every(delay, action, count=nil, after=nil, tag=nil)
  21. #     @timer.during(delay, action, after=nil, tag=nil)
  22. #     @timer.script{|wait| ...; wait.call(n); ... }
  23. #     @timer.tween(delay, subject, target, method, after=nil, tag=nil, *args, &update)
  24. #     after/every/tween # [delay]参数支持整数/范围类型
  25. #
  26. #     @timer.progress(tag)  # 查看定时器的进度(0~1)
  27. #     @timer.has?(tag, include=false)  # 是否有指定任务, 如果存在则返回任务, 不存在返回 nil
  28. #                                      # tag 支持正则表达式、字符串
  29. #                                      # include 表示是否以包含匹配(只在 tag 为字符串时有效)。
  30. #     Timer.tween_(t, a, b, m) # 类方法, 用来查看单步值
  31. #
  32. #   [范例]
  33. #
  34. #     # 添加一60帧后执行一次的定时
  35. #     @timer.after(60, proc { p 'after: 60帧后输出' })
  36. #
  37. #     # 添加一个每50帧循环执行的定时
  38. #     @timer.every(50, proc {|n| p "every: 每50帧输出一次, 当前第#{n}次" })
  39. #
  40. #     # 添加一个每50帧循环执行的定时, 循环次数为 4 次, 由于第一个时间参数为负数, 表示第一次循环不需要等待
  41. #     @timer.every(-50, proc { p 'every: 每50帧输出一次, 4次后结束' }, 4, proc{ p 'every: 执行完成' })
  42. #
  43. #     # 添加持续执行 2.5 秒时间的任务(持续循环执行,运行时间超出指定秒数后,则不再执行第二次, 但第一次不会中断)
  44. #     @timer.during(2.5, proc { p '我会持续执行2.5秒' }, proc{ p 'during执行完成' })
  45. #
  46. #     # 将附加块传入函数的内部创建Fiber,使用wait.call(n)不影响主线程进行等待,下面的代码相当于一个简化版的after集合。
  47. #     @timer.script{|wait|
  48. #       puts 1
  49. #       wait.call 60 # 等待60帧
  50. #       puts 2
  51. #       wait.call 60 # 等待60帧
  52. #       puts 3
  53. #     }
  54. #     
  55. #     # 上面的代码等同于下面的
  56. #     puts 1
  57. #     @timer.after(60, proc{
  58. #       puts 2
  59. #       @timer.after(60, proc{
  60. #         puts 3
  61. #       })
  62. #     })
  63. #
  64. #
  65. #   [Tween补间方法]
  66. #     [说明]
  67. #       tween 为补间(动画)方法, 用于对变量增减补间所用(绘制、显示等)
  68. #       定时器流程为调用 subject 对象中的【实例变量/Hash#Key/方法[v/v=]】来调整直到
  69. #       与 target 里存在的【实例变量/Hash#Key】值一致, 属性值只支持整数/小数。
  70. #     [渐变方式]
  71. #       'linear'
  72. #       'bezier'
  73. #       'in-out-' + method
  74. #       'out-in-' + method
  75. #       'in-' + method
  76. #       'out-' + method
  77. #     [渐变方法]
  78. #       'quad/cubic/quart/quint/sine/expo/circ/back/bounce/elastic/bezier'
  79. #     [Bezier]
  80. #       使用 bezier 补间方法需要在 tween 的 tag 参数后传入一个数组([x1, y1, x2, y2])
  81. #       例:@timer.tween(10, s, t, 'bezier', nil, nil, [0,0,1,1])
  82. #       或者:@timer.tween(10, s, t, CubicBezier.new(0,0,1,1))
  83. #       Bezier曲线图在线查看:https://cubic-bezier.com/
  84. #
  85. #     # tween范例:修改哈希
  86. #     subject = {:x => 50, :y => 10, :other => { :float => 0.0 } }
  87. #     target = {:x => 300, :y => 100, :other => { :float => 10.0 } }
  88. #     @timer.tween(120, subject, target, 'in-out-cubic', proc { p 'tween: 执行完成' })
  89. #     
  90. #     # tween范例:修改实例变量
  91. #     class Test; attr_accessor :value; def initialize(v); @value = v; end; end
  92. #     subject = Test.new(50)
  93. #     @timer.tween(120, subject, {value: 100}, 'in-out-cubic', proc { p 'tween: 执行完成' })
  94. #     
  95. #     # tween范例:没实例变量则修改方法(需要两个方法同时存在, 如:x/x=)
  96. #     sprite = Sprite.new; sprite.bitmap = Bitmap.new(50,50)
  97. #     @timer.tween(120, sprite, {x: 100, y: 50, src_rect: {width: 25}}, 'linear', proc { p 'tween: 执行完成' })
  98. #
  99. #     # tween范例:其他对象(此操作同理也是利用修改方法, x/x=  y/y=)
  100. #     s = Struct.new(:x, :y)[0, 0]
  101. #     @timer.tween(120, s, {x: 100, y: 100}, 'linear', proc { p 'tween: 执行完成' })
  102. #
  103. #     # tween范例:Target 也可以是非 Hash 的带有实例变量的对象(会检测target中所有实例变量来处理)
  104. #     class Test; attr_accessor :value; def initialize(v); @value = v; end; end
  105. #     t1 = Test.new(30); t2 = Test.new(100)
  106. #     @timer.tween(120, t1, t2, 'linear', proc { p 'tween: 执行完成' })
  107. #
  108. #     # tween范例:每帧更新回调
  109. #     @timer.tween(120, Sprite.new, {x: 10, src_rect: {width: 50}}, 'linear'){|t, i, r, k, v|
  110. #       p "#{t}, #{i}, #{r}, #{k}, #{v}"
  111. #
  112. #             # t 当前定时对象, t[:time] 即为当前帧
  113. #             # i (0当前帧更新前/1对象赋值前/2对方赋值后/3当前帧更新后)
  114. #             # r 操作的对象
  115. #             # k 操作的属性
  116. #             # v (要增加的值/增加后的值)
  117. #
  118. #     }
  119. #
  120. #     # tween范例:错误忽略
  121. #     $spr = Sprite.new
  122. #     @timer.tween(6000, $spr, {x: 10, _try_: true}, 'linear')
  123. #       # target里声明_try_为真, 则表示在计时器执行中忽略错误,
  124. #       # 这时在计时器执行中如果$spr执行了dispose方法,
  125. #       # 定时器则会忽略错误不会报错导致游戏停止运行。
  126. #
  127. #     # tween范例(单步取值)
  128. #     Timer.tween_(0.3, 100, 200, 'linear') # 返回 100->200 使用 linear 方法 30% 进度的值
  129. #
  130. #     [target参数特殊属性]
  131. #        _cb_(Proc):作用与 tween 的附加区块功能类似。
  132. #                    参数为(对象, 当前帧), 会在当前属性调用完毕后调用一次 _cb_ 。
  133. #
  134. #        _try_(Boolean):设置为true后, 定时器的任务触发错误时不会停止。
  135. #
  136. #        _before_(Hash):设置属性的初始值。
  137. #
  138. #==============================================================================

  139. class Timer
  140.   #--------------------------------------------------------------------------
  141.   # ● config
  142.   #--------------------------------------------------------------------------
  143.   TWEEN_METHOD_ASYNCHRONOUS = false # 异步, 默认关(开启后多个tween操作同一对象的方法时, 所取得的属性是否独立/共用(默认))
  144.   #--------------------------------------------------------------------------
  145.   # ● attr
  146.   #--------------------------------------------------------------------------
  147.   attr_reader :timer
  148.   #--------------------------------------------------------------------------
  149.   # ● initialize
  150.   #--------------------------------------------------------------------------
  151.   def initialize
  152.     @timer = {}
  153.     @_attr = Hash.new{|h,k| h[k] = Hash.new{|h2,k2| h2[k2] = {} } } # attr->tag->obj->key
  154.   end
  155.   #--------------------------------------------------------------------------
  156.   # ● dispose / disposed?
  157.   #--------------------------------------------------------------------------
  158.   def dispose; return if disposed?; self.clear; @timer = @_attr = nil; end
  159.   def disposed?; self.timer.nil?; end
  160.   #--------------------------------------------------------------------------
  161.   # ● clear
  162.   #--------------------------------------------------------------------------
  163.   def clear
  164.     @_attr.clear if @_attr
  165.     self.timer.clear
  166.   end
  167.   #--------------------------------------------------------------------------
  168.   # ● progress
  169.   #--------------------------------------------------------------------------
  170.   def progress(tag)
  171.     return nil unless t = has?(tag)
  172.     return t[:time] / t[:delay].to_f
  173.   end
  174.   #--------------------------------------------------------------------------
  175.   # ● has?
  176.   #--------------------------------------------------------------------------
  177.   def has?(tag, include=false)
  178.     if tag.is_a?(String) then
  179.       if include then
  180.         self.timer.find{|k, v| k.include?(tag) }
  181.       else
  182.         self.timer[tag]
  183.       end
  184.     elsif tag.is_a?(Regexp) then
  185.       self.timer.find{|k, v| k =~ tag }
  186.     end
  187.   end
  188.   #--------------------------------------------------------------------------
  189.   # ● update
  190.   #--------------------------------------------------------------------------
  191.   def update(tags=nil)
  192.     tags = tags ? [tags].flatten : self.timer.keys
  193.     for tag in tags do
  194.       timer = has?(tag)
  195.       next unless timer
  196.       timer[:time] += 1
  197.       case timer[:type]
  198.       when :after
  199.         if timer[:time] >= timer[:delay] then
  200.           timer[:action].call
  201.           self.cancel(tag)
  202.         end
  203.       when :every
  204.         if timer[:time] >= timer[:delay] then
  205.           timer[:action].call timer[:counter], timer[:delay]
  206.           timer[:time] -= timer[:delay]
  207.           timer[:delay] = _getResolvedDelay(timer[:any_delay], true)
  208.           timer[:counter] += 1
  209.           if timer[:count] > 0 then
  210.             if timer[:counter] >= timer[:count] then
  211.               timer[:after].call if timer[:after] != nil
  212.               self.cancel(tag)
  213.             end
  214.           end
  215.         end
  216.       when :during
  217.         if Graphics.frame_count.to_f / Graphics.frame_rate - (timer[:time] -= 1) <= timer[:delay] then
  218.           timer[:action].call
  219.         else
  220.           timer[:after].call if timer[:after] != nil
  221.           self.cancel(tag)
  222.         end
  223.       when :tween
  224.         ps = timer[:time]/timer[:delay].to_f
  225.         s = _tween(timer[:method], ps > 1 ? 1 : ps, *timer[:args])
  226.         ds = s - timer[:last_s]
  227.         timer[:last_s] = s
  228.         timer[:update].call(timer, 0) if timer[:update]
  229.         for _,info in timer[:payload] do
  230.           ref,key,delta,initial,type,param = info
  231.           cb,try,before = param
  232.           add = delta*ds
  233.           timer[:update].call(timer, 1, ref, key, add) if timer[:update]
  234.           begin
  235.             _v = timer[:time] == 1 ? before[key] : nil
  236.             case type
  237.             when -1  # hash
  238.               _v = ref[key] unless _v
  239.               _v += add
  240.               # Accuracy
  241.               if timer[:time] >= timer[:delay] then
  242.                 _v = _v.round(initial.class == Float ? initial.to_s.split('.')[1].size : 0)
  243.               end
  244.               ref[key] = _v
  245.             when 0    # variable
  246.               key = "@#{key}" unless key.to_s.include?('@')
  247.               _v = ref.instance_variable_get(key) unless _v
  248.               _v += add
  249.               # Accuracy
  250.               if timer[:time] >= timer[:delay] then
  251.                 _v = _v.round(initial.class == Float ? initial.to_s.split('.')[1].size : 0)
  252.               end
  253.               ref.instance_variable_set(key, _v)
  254.             when 1    # method
  255.               ref_id = ref.__id__
  256.               data = @_attr[tag]
  257.               @_attr.values.find{|v| data[ref_id] = v[ref_id] } unless TWEEN_METHOD_ASYNCHRONOUS
  258.               data[ref_id][key] = _v if _v
  259.               _v = data[ref_id][key] ||= ref.__send__(key)
  260.               _v += add
  261.               # Accuracy
  262.               if timer[:time] >= timer[:delay] then
  263.                 _v = _v.round(initial.class == Float ? initial.to_s.split('.')[1].size : 0)
  264.               end
  265.               ref.__send__("#{key}=", data[ref_id][key] = _v)  # Fine-tuning
  266.             end
  267.           rescue Exception => e
  268.             raise e unless try
  269.           end
  270.           cb.call(ref, timer[:time]-1) if cb
  271.           timer[:update].call(timer, 2, ref, key, _v) if timer[:update]
  272.         end
  273.         timer[:update].call(timer, 3) if timer[:update]
  274.         if timer[:time] >= timer[:delay] then
  275.           timer[:after].call if timer[:after] != nil
  276.           self.cancel(tag)
  277.         end
  278.       end
  279.     end
  280.   end
  281.   #--------------------------------------------------------------------------
  282.   # ● cancel
  283.   #--------------------------------------------------------------------------
  284.   def cancel(*tags)
  285.     tags.each do |t|
  286.       if t.is_a?(Regexp) then
  287.         cancel(*self.timer.keys.select{|k| k =~ t })
  288.       else
  289.         @_attr.delete(t)
  290.         self.timer.delete(t)
  291.       end
  292.     end
  293.   end
  294.   #--------------------------------------------------------------------------
  295.   # ● after
  296.   #--------------------------------------------------------------------------
  297.   def after(delay, action, tag=nil)
  298.     tag ||= UUID()
  299.     self.cancel(tag)
  300.     self.timer[tag] = {
  301.       :tag=>tag,
  302.       :type=>:after,
  303.       :time=>0,
  304.       :delay=>_getResolvedDelay(delay),
  305.       :action=>action,
  306.     }
  307.     return tag
  308.   end
  309.   #--------------------------------------------------------------------------
  310.   # ● every
  311.   #--------------------------------------------------------------------------
  312.   def every(delay, action, count=nil, after=nil, tag=nil)
  313.     if count.is_a?(String) then
  314.       tag, count = count, 0
  315.     elsif count.is_a?(Fixnum) and after.is_a?(String) then
  316.       tag, after = after, nil
  317.     end
  318.     tag ||= UUID()
  319.     self.cancel(tag)
  320.     t = _getResolvedDelay(delay)
  321.     t = t.abs if first = t < 0 # The first cycle does not need to wait
  322.     self.timer[tag] = {
  323.       :tag=>tag,
  324.       :type=>:every,
  325.       :time=>first ? t : 0,
  326.       :any_delay=>delay,
  327.       :delay=>t,
  328.       :action=>action,
  329.       :counter=>0,
  330.       :count=>count || 0,
  331.       :after=>after,
  332.     }
  333.     return tag
  334.   end
  335.   #--------------------------------------------------------------------------
  336.   # ● during
  337.   #--------------------------------------------------------------------------
  338.   def during(delay, action, after=nil, tag=nil)
  339.     if after.is_a?(String) then
  340.       tag, after = after, nil
  341.     end
  342.     tag ||= UUID()
  343.     self.cancel(tag)
  344.     self.timer[tag] = {
  345.       :tag=>tag,
  346.       :type=>:during,
  347.       :time=>Graphics.frame_count.to_f / Graphics.frame_rate,
  348.       :delay=>delay,
  349.       :action=>action,
  350.       :after=>after,
  351.     }
  352.     return tag
  353.   end
  354.   #--------------------------------------------------------------------------
  355.   # ● script
  356.   #--------------------------------------------------------------------------
  357.   def script
  358.     return unless block_given?
  359.     f = Fiber.new{|wait| yield(wait) }
  360.     f.resume(proc{|t| self.after(t, proc{ f.resume }); Fiber.yield })
  361.   end
  362.   #--------------------------------------------------------------------------
  363.   # ● tween
  364.   #--------------------------------------------------------------------------
  365.   def tween(delay, subject, target, method, after=nil, tag=nil, *args, &update)
  366.     if after.is_a?(String) then
  367.       after, tag = nil, after
  368.     end
  369.     tag ||= UUID()
  370.     self.cancel(tag)
  371.     self.timer[tag] = {
  372.       :tag=>tag,
  373.       :type=>:tween,
  374.       :time=>0,
  375.       :delay=>_getResolvedDelay(delay),
  376.       :subject=>subject,
  377.       :target=>target,
  378.       :method=>method,
  379.       :update=>update,
  380.       :after=>after,
  381.       :args=>args,
  382.       :last_s=>0,
  383.       :payload=>tweenCollectPayload(subject, target, {}),
  384.     }
  385.     return tag
  386.   end
  387.   #--------------------------------------------------------------------------
  388.   # ● _getResolvedDelay
  389.   #--------------------------------------------------------------------------
  390.   def _getResolvedDelay(delay, abs=false)
  391.     case delay
  392.     when Numeric
  393.       return abs ? delay.abs : delay
  394.     when Range
  395.       a, b = delay.first, delay.last
  396.       return a+rand(b-a+(delay.exclude_end? ? 0 : 1))
  397.     end
  398.   end
  399.   #--------------------------------------------------------------------------
  400.   # ● tweenCollectPayload
  401.   #--------------------------------------------------------------------------
  402.   def tweenCollectPayload(subject, target, out)
  403.     unless target.is_a?(Hash) # object convert to hash.
  404.       hash = {}
  405.       target.instance_variables.each do |var|
  406.         hash[var.to_sym] = target.instance_variable_get(var)
  407.       end
  408.       target = hash
  409.     end
  410.     keys = target.select{|k, v| v.is_a?(Numeric) }.keys
  411.     before = target[:_before_] || {}
  412.     for k, v in target do
  413.       next if [:_cb_, :_try_, :_before_].include?(k) # callback ignore
  414.       # with instance attribute
  415.       ref = (subject.is_a?(Hash) ? subject[k] : subject.instance_variable_get('@' << k.to_s))
  416.       # with method(method/method=)
  417.       ref_ = nil
  418.       if ref.nil? then
  419.         ref = ref_ = begin
  420.           subject.__send__(k)
  421.         rescue Exception => e
  422.           puts e.message
  423.           raise RGSSError.new("#{self.to_s.insert(-2, '#tween')}: error from method `#{k}' in subject(#{subject}).\nThere are method(#{k}) in target, maybe not in subject ?")
  424.         end
  425.       end
  426.       if v.is_a?(Numeric) then
  427.         raise TypeError.new("#{self.to_s.insert(-2, '#tween')}: wrong class type `#{k}' in subject of (#{ref.class} for Numeric)") unless ref.is_a?(Numeric)
  428.         delta = v - (before[k] || ref)
  429.         out[out.size+1] = [
  430.           subject, k, delta, v,
  431.           (ref_.nil? ? (subject.is_a?(Hash) ? -1 : 0) : 1),
  432.           [
  433.             k == keys[-1] ? target[:_cb_] : nil,
  434.             target[:_try_],
  435.             before,
  436.           ],
  437.         ]
  438.       else  # Hash or Object , Continue recursion
  439.         tweenCollectPayload(ref, v, out)
  440.       end
  441.     end
  442.     return out
  443.   end
  444.   #--------------------------------------------------------------------------
  445.   # ● tween step
  446.   #--------------------------------------------------------------------------
  447.   def self.tween_(t, a, b, m)
  448.     @@timer ||= self.new
  449.     t >= 1 ? b : @@timer.instance_eval{ _tween(m, t) } * (b-a) + a
  450.   end
  451.   #--------------------------------------------------------------------------
  452.   # ● _tween
  453.   #--------------------------------------------------------------------------
  454.   def _tween(method, *args)
  455.     t = {
  456.       :out => proc{|f| proc {|s,*a| 1 - f.call(1-s, *a) } },
  457.       :chain => proc{|f1,f2| proc {|s,*a| (s < 0.5 ? f1.call(2*s, *a) : 1 + f2.call(2*s-1, *a))*0.5 } },
  458.       :linear => proc{|s| s },
  459.       :quad => proc{|s| s ** 2 },
  460.       :cubic => proc{|s| s ** 3 },
  461.       :quart => proc{|s| s ** 4 },
  462.       :quint => proc{|s| s ** 5 },
  463.       :sine => proc{|s| 1-Math.cos(s*Math::PI/2) },
  464.       :expo => proc{|s| 2 ** (10*(s-1)) },
  465.       :circ => proc{|s| 1-Math.sqrt(1-s*s) },
  466.       :back => proc{|s, bounciness| bounciness ||= 1.70158; s*s*((bounciness+1)*s - bounciness) },
  467.       :bounce => proc{|s| a, b = 7.5625, 1/2.75; [a*s**2, a*(s-1.5*b)**2 + 0.75, a*(s-2.25*b)**2 + 0.9375, a*(s-2.625*b)**2 + 0.984375].min },
  468.       :elastic => proc{|s, amp, period| amp, period = (amp ? [1, amp].max : 1), (period ? period : 0.3); (-amp*Math.sin(2*Math::PI/period*(s-1) - Math.asin(1/amp)))*2**(10*(s-1)) },
  469.       :bezier => proc{|s, arr| CubicBezier.new(*arr).solve(s) },
  470.     }
  471.     if method.is_a?(CubicBezier)
  472.       return method.solve(args[0])
  473.     elsif method == 'linear' then
  474.       return t[:linear].call(*args)
  475.     elsif method == 'bezier' then
  476.       return t[:bezier].call(*args)
  477.     elsif method[0...7] == 'in-out-' then
  478.       met = t[method[7..-1].to_sym]
  479.       f1 = met
  480.       f2 = t[:out].call(met)
  481.       return t[:chain].call(f1, f2).call(*args)
  482.     elsif method[0...7] == 'out-in-' then
  483.       met = t[method[7..-1].to_sym]
  484.       f1 = t[:out].call(met)
  485.       f2 = met
  486.       return t[:chain].call(f1, f2).call(*args)
  487.     elsif method[0...4] == 'out-' then
  488.       met = t[method[4..-1].to_sym]
  489.       return t[:out].call(met).call(*args)
  490.     elsif method[0...3] == 'in-' then
  491.       met = t[method[3..-1].to_sym]
  492.       return met.call(*args)
  493.     end
  494.   end
  495.   #--------------------------------------------------------------------------
  496.   # ● UUID
  497.   #--------------------------------------------------------------------------
  498.   KEY = ('A'..'Z').to_a + (0..9).to_a
  499.   def UUID()
  500.     i = KEY.shuffle.first(10).join
  501.     return (self.timer[i].nil? ? i : UUID())
  502.   end
  503.   #--------------------------------------------------------------------------
  504.   # ● detection disposed?
  505.   #--------------------------------------------------------------------------
  506. #~   old = {}
  507. #~   %w(cancel after every during script tween progress clear has? update).each do |name|
  508. #~     sym  = name.to_sym
  509. #~     old[sym] = instance_method(sym)
  510. #~     define_method sym do |*args|
  511. #~       raise RGSSError.new "disposed #{self.class} from :#{sym}" if disposed?
  512. #~       old[sym].bind(self).call(*args)
  513. #~     end
  514. #~   end
  515.   private :_getResolvedDelay, :tweenCollectPayload, :_tween, :UUID
  516. end

  517. #==============================================================================
  518. # ■ CubicBezier
  519. #==============================================================================
  520. class CubicBezier
  521.   private
  522.   def initialize(p1x, p1y, p2x, p2y)
  523.     @cx = 3.0 * p1x
  524.     @bx = 3.0 * (p2x - p1x) - @cx
  525.     @ax = 1.0 - @cx - @bx

  526.     @cy = 3.0 * p1y
  527.     @by = 3.0 * (p2y - p1y) - @cy
  528.     @ay = 1.0 - @cy - @by
  529.   end
  530.   def sampleCurveX(t)
  531.     ((@ax * t + @bx) * t + @cx) * t
  532.   end
  533.   def sampleCurveY(t)
  534.     ((@ay * t + @by) * t + @cy) * t
  535.   end
  536.   def sampleCurveDerivativeX(t)
  537.     (3.0 * @ax * t + 2.0 * @bx) * t + @cx
  538.   end
  539.   ZERO_LIMIT = 1e-6
  540.   def solveCurveX(x)
  541.     t2 = x
  542.     x2 = 0
  543.     derivative = 0
  544.     8.times do |i|
  545.       x2 = sampleCurveX(t2) - x
  546.       return t2 if x2.abs < ZERO_LIMIT
  547.       derivative = sampleCurveDerivativeX(t2)
  548.       break if derivative.abs < ZERO_LIMIT
  549.       t2 -= x2 / derivative
  550.     end

  551.     t1 = 1
  552.     t0 = 0
  553.     t2 = x
  554.     while t1 > t0
  555.       x2 = sampleCurveX(t2) - x
  556.       return t2 if x2.abs < ZERO_LIMIT
  557.       if x2 > 0
  558.         t1 = t2
  559.       else
  560.         t0 = t2
  561.       end
  562.       t2 = (t1 + t0) / 2
  563.     end
  564.     return t2
  565.   end
  566.   public
  567.   def solve(x)
  568.     sampleCurveY(solveCurveX(x))
  569.   end
  570. end

  571. #~ # bezier = CubicBezier.new(0,0,1,1)
  572. #~ bezier = CubicBezier.new(0.25,0.1,0.25,1)
  573. #~ s = Sprite.new
  574. #~ b = s.bitmap = Bitmap.new(300,300)
  575. #~ b.fill_rect(b.rect, Color.new(255,0,0))
  576. #~ b.width.times do |i|
  577. #~   arr = [i, (b.height-bezier.solve(i/b.width.to_f)*b.height).to_i]
  578. #~   b.set_pixel(*arr, Color.new(255,255,255))
  579. #~ end

  580. #~ loop do
  581. #~   Graphics.update
  582. #~   Input.update
  583. #~ end
复制代码


Tween算法演示(更新)
html演示效果(来源网络): Tween.zip (4.5 KB, 下载次数: 12)
1.gif
2.gif
3.gif


更新内容
【v1.1更新_2018.09.07】
1.tween参数(subject/target)支持Object对象。(共支持hash、object)

【v1.2更新_2018.09.19】
1.tween对小数处理的精度问题。

【v1.3更新_2018.09.28】
1.tween支持方法读取/更改(v/v=)。
2.修复定时器套用定时器产生的问题。

【v1.4更新_2018.10.03】
1.tween末尾传递的参数(*args)未生效的问题。

【v1.5更新_2018.10.06】
1.tween参数对象subject的检测方法支持method_missing。

【v1.6更新_2018.10.09】
1.tween修复精度。
2.tween对方法修改的bug。
3.tween同时执行多条计时,对相同对象属性修改的机制修改。
4.扩大随机的UUID。
5.优化脚本。

【v1.7更新_2018.11.14】
1.tween支持格式加强,支持嵌套。
  例:timer.tween(60, sprite, {x: 10, src_rect: {width: 50}}, 'linear')

【v1.8更新_2018.11.16】
1.新增script实例方法。(将方法附加块传入函数的内部创建Fiber,使用wait.call(n)不影响主线程进行等待,下面的代码相当于一个简化版的after集合。)
  1.   # 范例
  2.   @timer.script{|wait|
  3.     puts 1
  4.     wait.call 60 # 等待60帧
  5.     puts 2
  6.     wait.call 60 # 等待60帧
  7.     puts 3
  8.   }
  9.   
  10.   # 上面的代码执行结果等同于下面的
  11.   puts 1
  12.   @timer.after(60, proc{
  13.     puts 2
  14.     @timer.after(60, proc{
  15.       puts 3
  16.     })
  17.   })
复制代码


【v1.9更新_2018.12.27】
1.every的action增加一条参数传递,用来获取执行的第几次。
例:timer.every(1, proc{|n| puts n } )

【v2.0更新_2019.01.25】
1.修改了during的作用(持续循环执行一个任务N秒,如果执行时间过长超出限制秒数则不会强制中断)。

【v2.1更新_2019.06.18】
1.修复了一个bug。

【v2.2更新_2019.09.28】
1.优化tween。
2.新增实例方法:
        disposed? # 定时器是否已释放
        clear        # 清除计时器所有任务

【v2.35更新_2019.10.14】
1.修复cancel方法未能即时生效的问题。
2.tween的method方法中@_attr重复记录对象导致的属性变动异常问题。

【v2.36更新_2020.03.11】
1.兼容重复 dispose 导致的出错。
2.添加progress(tag)方法, 查看计时器完成进度(0~1)。
3.cancel方法支持多参数,可以传多个tag。

【v2.37更新_2020.03.13】
1.新支持:every 方法第一个参数如果是负数, 则表示第一次循环不需要等待。

【v2.38更新_2020.03.15】
1.新增类方法:
        tween_ # 用来获取 tween 的单步值。
                   # 例:Timer.tween_(0.3, 100, 200, 'linear') # 返回 100->200 使用 linear 方法 30% 进度的值

【v2.5更新_2020.03.27】
1.使用__send__方法来替换之前的send方法调用, 避免对象自定义send方法后调用导致出错。
2.使用__id__方法来替换之前的hash方法调用, 避免对象自定义hash方法后调用导致出错。

【v2.6更新_2020.03.30】
1.cancel/progress 方法支持正则表达式。
2.update(tag=nil) 方法传入tag标签或数组,可以手动更新指定的定时器(支持正则表达式)。
3.新增实例方法:
        has?(tag, include=false)  查看是否有指定任务, 如果存在则返回任务, 不存在返回 nil
                                                        tag 支持正则表达式或字符串。
                                                        include 表示是否以包含匹配(只在 tag 为字符串时有效)。
4.优化脚本。

【v2.7更新_2020.05.26】
1.tween支持传附加区块进行回调。
        tween(...){|t, i, r, k, v| p "#{t}, #{i}, #{r}, #{k}, #{v}" }
        # t 当前定时对象, t[:time] 即为当前帧
        # i (0当前帧更新前/1对象赋值前/2对方赋值后/3当前帧更新后)
        # r 操作的对象
        # k 操作的属性
        # v (要增加的值/增加后的值)
2.优化注释、异常错误的提示。
3.优化脚本。

【v2.8更新_2020.08.27】
1.加入 TWEEN_METHOD_ASYNCHRONOUS 常量属性,设置 tween 的方法是否异步。
2.[after/every/tween] # 该方法的[delay]参数支持整数/范围类型, every 使用范围参数每次循环都会在范围内随机。
3.tween 的 target 对象可以添加 _cb_(Proc) , 作用与 tween 的附加区块功能类似。参数为(对象, 当前帧), 会在当前属性调用完毕后调用一次 _cb_ 。

【v2.9更新_2021.01.31】
1.tween新增bezier补间方法。
  需要在 tween 的 tag 参数后传入一个数组([x1, y1, x2, y2])
  例:@timer.tween(10, s, t, 'bezier', nil, nil, [0,0,1,1])
        @timer.tween(10, s, t, 'in-out-bezier', nil, nil, [0.42,0,1,1])
        @timer.tween(10, s, t, 'in-bezier', nil, nil, [0.25,0.1,0.25,1])
        @timer.tween(10, s, t, CubicBezier.new(0,0,1,1))
  Bezier曲线图在线查看:https://cubic-bezier.com/

【v3.0更新_2022.01.16】
3.tween 的 target 对象可以添加 _before_(Hash) , 可以设置subject的初始属性。
3.tween 的 target 对象可以添加 _try_(Boolean) , 设置为 true 后定时任务出错后不会停止。

旧版下载链接


范例范例一
1.png

范例二
2.png

范例三
1.png
  1. bit = Bitmap.new(10,10).tap{|b| b.fill_rect(b.rect, Color.new(255,0,0)) }
  2. arr = 10.times.map{ {s: Sprite.new.tap{|s| s.bitmap = bit }, r: -1.57} }

  3. timer = Timer.new
  4. timer.every(10, proc{|i|
  5.   t = 180
  6.   timer.every(-t, proc{
  7.     timer.tween(t, arr[i], {r: arr[i][:r]+Math::PI*2}, 'in-out-cubic')
  8.     timer.every(1, proc{
  9.       s, r = arr[i][:s], arr[i][:r]
  10.       s.x, s.y = 272+Math.cos(r)*50, 208+Math.sin(r)*50
  11.     }, t)
  12.   })
  13. }, 10) # 创建好任务, 只需要交给 timer 的 update 来执行即可

  14. loop do
  15.   Graphics.update
  16.   timer.update
  17. end
复制代码



使用帮助在脚本说明里面,利于执行/简化脚本、坐标/属性变动、循环执行任务、tween动画等。
范例下载:

[RM]定时器v3.0.7z (1.42 MB, 下载次数: 280)

评分

参与人数 6赞 +6 收起 理由
刈飒的风 + 1 塞糖
zyf722 + 1 精品文章
唐咚咚 + 1 精品文章
gforce + 1 塞糖
baxiumeng + 1 塞糖
有丘直方 + 1 精品文章

查看全部评分

梦石
0
星屑
1408
在线时间
831 小时
注册时间
2007-12-25
回帖
1406
发表于 2020-4-26 11:22:35 | 显示全部楼层
没安装VA,所以打不开。
只是随便说说:
你写脚本很厉害的,没有注释,有也是英文。
另外,update能不能塞到Graphics.update里面。
精卫赤龙腾    九
总是存在一种强大,去完成似乎不可能的事情.
无畏战乾程    夜
或是需要一种勇气,去挑战几乎不存在的胜利.
一味玄真魂     神
这是拥有一种恒心,去化解根本没有解的困难.
烈卫开天径    尊
只是带着一种决心,去争取残存的最后的希望。
回复

使用道具 举报

梦石
0
星屑
19426
在线时间
3082 小时
注册时间
2013-1-11
回帖
1207
 楼主| 发表于 2020-4-26 12:00:56 | 显示全部楼层
本帖最后由 张咚咚 于 2020-4-26 12:02 编辑
九夜神尊 发表于 2020-4-26 11:22
没安装VA,所以打不开。
只是随便说说:
你写脚本很厉害的,没有注释,有也是英文。


可以,重写下Graphics就行了,使用$timer调用
  1. class << Graphics
  2.   alias :qqeat_timer_graphics_update :update unless $@
  3.   def update
  4.     qqeat_timer_graphics_update
  5.     $timer ||= Timer.new
  6.     $timer.update
  7.   end
  8. end
复制代码

脚本里面的英文注释是为了整齐一点(好多不会的词都是去翻译得到的233)

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册会员

本版积分规则

Powered by Discuz! X5.0 © 2001-2026 Discuz! Team.

在本版发帖返回顶部