# Fade colors in Corona using Transitions

March 11th, 2018 - SoftwareTutorial(1 min)

Corona provides transitions. According to this post, a `transitionTo(...)` would suffice:

``````local rect = display.newRect(50,50,100,100)
rect:setFillColor(0,0,0,0)
transition.to( rect.fill, { r=1, g=1, b=1, a=1,
time=500,
transition=easing.inCubic }
)``````

The user can also cancel the transition if needed (which is waht I would need to do later in the code). In case you’re into custom stuff and the easing functions are not enough, you can create your own. A sample can be found here.

The signature of the easing function is (at the moment of writing) `function customEasing(t, tMax, start, delta)` where:

• `t` is the time elapsed since the start
• `tMax` is the duration of the transition
• `start` is 1 if `t` in this call of the easing function differs from the `t` in the last call, otherwise 0
• `delta` is 1 if is the last acall of the easign function with the same value of `t`

An example is:

ttMaxstartdelta
21:49:21.088 948.4300000
21:49:21.088 948.4300001
21:49:21.108 960.2300010
21:49:21.108 960.2300000
21:49:21.108 960.2300000
21:49:21.108 960.2300001
21:49:21.119 975300010
21:49:21.119 975300000
21:49:21.119 975300000
21:49:21.119 975300001

The data from above table was created using the following easing function:

``````local function customEasing(t, tMax, start, delta)
print (t .. " | " .. tMax .. " | " .. start .. " | " .. delta)
return start
end``````

IMPORTANT: The easing function must return relevant data for the value being transitioned!

NOTABLE: A final call is made with the final value of the transition, regardless of the easing function.

Now it’s easy to create custom transition functions.

There are advantages and disadvantages of using this approach comared to the previous post (game loop approach). Advantages are:

• Code is significantly leaner
• You can concentrate to writing your own easing function instead of folling your source with boilerplate
• The table above shows this function gets called serveral times for each frame, arguably allowing finer transition calculations

• A continuous change means we need to restart the transition while in the game loop approach it would mean wwe only need to change the business logic to accomodate the changes.
• There is a risk to perform needless calculations in the easing function, resulting in pointless use of resources

Which is the best approach? I think it depends… If you only need to e.g. fade in/out an image, then a transition is the way to go. If you need to cycle through colors, then it depends on your requirements (e.g. accuracy, control).

In my case I’ll need to continuously cycle through colors so I’m leaning towards the game loop approach.

HTH,

Tagged with
All Tags
Share on

A little experiment: