制作三次缓入曲线可动态切换其目标位置

时间:2019-02-22 03:36:48

标签: lua interpolation cubic

使用Lua,我已经实现了从一个数字到另一个进行三次插值(先缓入/“加速”,然后缓和/缓和)的功能。 SimpleSpline的取值范围为0-1(动画进行的时间,最容易放置),而SimpleSplineBetween的取值范围相同,但是将其保持在两个给定的最小值/最大值之间。

function SimpleSpline( v )
    local vSquared = v*v
    return (3 * vSquared - 2 * vSquared * v)
end

function SimpleSplineBetween( mins, maxs, v )
    local fraction = SimpleSpline( v )
    return (maxs * fraction + mins * (1 - fraction))
end

一切正常。但是,我遇到了一个问题。我希望它更具动态感。例如,假设我的“最小值”是0.5,而我的“最大值”是1,那么我有一个变量,表示我作为V传递的时间;我们说它是0.5,所以我们当前的插值是0.75。现在,我们还假设“最大值”突然上升到0.25,因此,现在,我们有了一个新的目标。

我目前用于处理上述情况的方法是重置“时间”变量并将“分钟”更改为当前值;在上述情况下为0.75等。但是,由于动画已完全重置,因此在动画中会产生非常明显的“停止”或“冻结”。

我的问题是,如何在不停止的情况下实现动态变化?我希望它可以从一个目标编号平稳地过渡到另一个目标编号。

1 个答案:

答案 0 :(得分:-1)

local Start_New_Spline, Calculate_Point_on_Spline, Recalculate_Old_Spline
do

   local current_spline_params

   local function Start_New_Spline(froms, tos)
      current_spline_params = {d=0, froms=froms, h=tos-froms, last_v=0}
   end

   local function Calculate_Point_on_Spline(v)  --  v = 0...1
      v = v < 0 and 0 or v > 1 and 1 or v
      local d     = current_spline_params.d
      local h     = current_spline_params.h
      local froms = current_spline_params.froms
      current_spline_params.last_v = v
      return (((d-2*h)*v+3*h-2*d)*v+d)*v+froms
   end

   local function Recalculate_Old_Spline(new_tos)
      local d     = current_spline_params.d
      local v     = current_spline_params.last_v
      local h     = current_spline_params.h
      local froms = current_spline_params.froms
      froms = (((d-2*h)*v+3*h-2*d)*v+d)*v+froms
      d = ((3*d-6*h)*v+6*h-4*d)*v+d
      current_spline_params = {d=d, froms=froms, h=new_tos-froms, last_v=0}
   end

end

根据您的值使用示例:

Start_New_Spline(0.5, 1)      -- "mins" is 0.5, "maxs" is 1
local inside_spline = true
while inside_spline do
   local goal_has_changed = false
   for time = 0, 1, 0.015625 do  -- time = 0...1
      -- It's time to draw next frame
      goal_has_changed = set to true when goal is changed
      if goal_has_changed then
         -- time == 0.5 ->  s == 0.75, suddenly "maxs" is jerked up to 0.25
         Recalculate_Old_Spline(0.25)  -- 0.25 is the new goal
         -- after recalculation, "time" must be started again from zero
         break  -- exiting this loop
      end
      local s = Calculate_Point_on_Spline(time)  -- s = mins...maxs
      Draw_something_at_position(s)
      wait()
   end
   if not goal_has_changed then
      inside_spline = false
   end
end