Page 1 of 1

Tween builder

Posted: Tue Aug 08, 2017 8:02 am
by xsw
I built a small utility on top of the excellent hump timer lib. Maybe someone will find it useful.

I found it was a pain to chain together tween calls using the callback functionality. So I made a builder which makes chaining tweens easy.

With this you can for example do this (which would be a pain using callbacks):

x from 0 to 5,
wait 2 sec
y from 0 to 5

local o = { x = 0, y = 0 }

TweenBuilder(timer)
:tween(1, o, {x=5})
:delay(2)
:tween(1, o, {y=5})
:start(function() print("Done") end)

Here is the code:

Code: Select all

local TweenBuilder = function(timer)
    local queue = {}

    return {
        tween = function(self, duration, subject, target, method)
            table.insert(queue, function(after)
                timer:tween(duration, subject, target, method or 'linear', after)
            end)
            return self
        end,

        delay = function(self, duration)
            table.insert(queue, function(after)
                timer:after(duration, after)
            end)
            return self
        end,

        start = function(self, doneFunc)
            local function next(i)
                if i > #queue then return doneFunc end
                return function() queue[i](next(i+1)) end
            end
            next(1)()
        end
    }
end

Re: Tween builder

Posted: Tue Aug 08, 2017 3:22 pm
by shru
This is cool, chaining timers is definitely a common use case for myself.

This gives me another idea, actually. I might fork hump.timer and make a version where a timer handle can be decorated with another timer which will be executed when the parent timer finishes. ie:

Code: Select all

Timer.tween(1, o, {x=5})
  :after(2, function() doTheThing() end)
  :every(0.2, function() doTheOtherThing() end, 5)
  -- etc
Essentially the same idea as yours, but with an easier to remember interface, perhaps?

Re: Tween builder

Posted: Wed Aug 09, 2017 11:05 am
by xsw
That would be even better :-).