Mixing two sprites preserving alpha channel

Mixing two sprites according to a percentage can be interesting, in order to fade from the first to the second one.

Let’s suppose for now that the two sprites have the same shape.

An initial idea: draw the first sprite with alpha 1, then draw the second sprite above the first one with the desired alpha.

This is not good for sprites with varying alpha channels: because all the pixels are drawn two times, semi transparent areas will be more opaque than they need to be.

So here is a shader that mixes two sprites correctly. It requires the second texture and the opacity parameter (between 0 and 1: 0 for the first texture, 1 for the second one).

Vertex shader:

Fragment shader:

Here is an example code that shows how to use it (Draw event):

Warning: if you have sprites with different shapes, you also need to premultiply alpha for both sprites, then draw using the following blend mode: